Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the order of facet labels in ggplot (custom facet wrap labels)

Tags:

r

ggplot2

I plotted a facet plot using ggplot and here is the plot

http://i.stack.imgur.com/5qXF1.png

The problem I have is, The facets(labels) are sorted alphabetically (Ex: E1, E10, E11,E13, E2, E3, I1, I10, I2) but I need them to be a custom order like E1, I1, E2, I2, E3, E10, I10, E11, E13.

How can I do that ?

like image 236
Jana Avatar asked Mar 30 '11 18:03

Jana


People also ask

How do I reorder facets in R?

To reorder the facets accordingly of the given ggplot2 plot, the user needs to reorder the levels of our grouping variable accordingly with the help of the levels function and required parameter passed into it, further it will lead to the reordering of the facets accordingly in the R programming language.

How do you rename a facet grid label?

Change the text of facet labels Facet labels can be modified using the option labeller , which should be a function. In the following R code, facets are labelled by combining the name of the grouping variable with group levels. The labeller function label_both is used.

How do I change the size of a facet label in ggplot2?

If we want to modify the font size of a ggplot2 facet grid, we can use a combination of the theme function and the strip. text. x argument. In the following R syntax, I'm increasing the text size to 30.

Can I facet wrap by two variables?

ggplot2 makes it easy to use facet_wrap() with two variables by simply stringing them together with a + . Although it's easy, and we show an example here, we would generally choose facet_grid() to facet by more than one variable in order to give us more layout control.


1 Answers

Don't rely on the default ordering of levels imposed by factor() or internally by ggplot if the grouping variable you supply is not a factor. Set the levels explicitly yourself.

dat <- data.frame(x = runif(100), y = runif(100),                    Group = gl(5, 20, labels = LETTERS[1:5])) head(dat) with(dat, levels(Group)) 

What if I want them in this arbitrary order?

set.seed(1) with(dat, sample(levels(Group))) 

To do this, set the levels the way you want them.

set.seed(1) # reset the seed so I get the random order form above dat <- within(dat, Group <- factor(Group, levels = sample(levels(Group)))) with(dat, levels(Group)) 

Now we can use this to have the panels drawn in the order we want:

require(ggplot2) p <- ggplot(dat, aes(x = x)) + geom_bar() p + facet_wrap( ~ Group) 

Which produces:

facets wrapped

like image 144
Gavin Simpson Avatar answered Sep 24 '22 23:09

Gavin Simpson