-1

In How to change the order of facet labels in ggplot (custom facet wrap labels) it is described how to add group levels for later use in a sorted facet grid.

How can I generate group levels to mtcars that will turn the number of cylinders in the reversed order?

Community
  • 1
  • 1
Jonas Stein
  • 6,826
  • 7
  • 40
  • 72
  • What is wrong with the answer provided in the question to which you linked? – mnel Nov 29 '12 at 01:29
  • `Group = gl(5, 20, labels = LETTERS[1:5])` assumes that I have 5*20 items, but how will I have to sort it with 30+50+20 items for example? – Jonas Stein Nov 29 '12 at 01:31
  • something like `within(mtcars, Group = factor(cylinder, levels = rev(sort(unique(cylinder))))` should suffice. – mnel Nov 29 '12 at 01:33
  • `within(mtcars, Group <- factor(cyl, levels = rev(sort(unique(cyl)))))`. typo on my behalf, (now has been tested) – mnel Nov 29 '12 at 01:48
  • works on mtcars and with my data too. Could you make it an answer? Thx. – Jonas Stein Nov 29 '12 at 01:52

1 Answers1

2

The trick here is to sort the unique values, and then set the levels as the reverse.

for example.

mtcars <- within(mtcars, Group <- factor(cyl, levels = rev(sort(unique(cyl)))))


ggplot(mtcars) + geom_point() + facet_grid(~Group)
mnel
  • 113,303
  • 27
  • 265
  • 254