ordering axis on facet plot using factor but including size in label

Viewed 104

I have this facet plot and the x axis I would like to make the ordering of the x axis to be "outside fav","ne","mi", "fa","outside un" but it is tricky because I also want to include a count of the observations in parentheses.

I made x be a factor and put the data frame in the right order like this:

 dat$x = factor(dat$x, levels = c("outside fav","ne","mi", "fa","outside un") , ordered = TRUE)
      levels(dat$x)
      dat = dat %>% arrange(country, x) # order by country and x 

Then in the ggplot below I do this:

factor( x_label, levels = unique(dat$x_label), ordered = TRUE)

to try to keep the labels in order but the unique of course now includes the count in the parentheses so the the output of the plot is not correct. You can see this by looking at the "J" plot where the order on the x axis is fa(5), outside fav (5) etc....

Do you know how to get the order on the x axis lables in the correct order WHILE including the count in parenthese?

Thank you.

  dat =  data.frame(country = c(
                                    rep("A",4),
                                    rep("H", 5),
                                    rep("I",4),
                                    rep("J", 5),
                                    rep("S", 2),
                                    rep("T",4)    ),
                       x = c(
                                     "outside fav","mi", "fa","outside un",
                                     "outside fav","ne","mi", "fa","outside un",
                                     "outside fav","mi", "fa","outside un",
                                     "outside fav","ne","mi", "fa","outside un",
                                      "fa","outside fa",
                                      "ne","mi", "fa","outside un"  ), 
                 x_label = c(
                                     "outside fav (1)","mi(3)", "fa (5)","outside un (3)",
                                     "outside fav (6)","ne (8)","mi (57)", "fa (22)","outside un (6)",
                                     "outside fav (27)","mi (2)", "fa (4)","outside un (41)",
                                     "outside fav (5)","ne (5)","mi (8)", "fa (5)","outside un (8)",
                                      "fa (3)","outside fa (2)",
                                      "ne (2)","mi (2)", "fa (2)","outside un (1)"  ),
                 y = rnorm(24)
                 )
      dat$x = factor(dat$x, levels = c("outside fav","ne","mi", "fa","outside un") , ordered = TRUE)
      levels(dat$x)
      dat = dat %>% arrange(country, x) # order by country and x 
      ggplot(dat, aes(x = factor( x_label, levels = unique(dat$x_label), ordered = TRUE),
                      y = y   ))+ 
        geom_point()  +
        facet_wrap(~country, scales="free_x")+theme(axis.text.x = element_text(angle = 90))
2 Answers
Related