Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reorder() not correctly reordering a factor variable in ggplot

Tags:

r

ggplot2

I'm baffled as to why the boxplots are not ordering in this plot:

set.seed(200)
x <- data.frame(country=c(rep('UK', 10), 
                          rep("USA", 10), 
                          rep("Ireland", 5)),
                wing=c(rnorm(25)))

ggplot(x, aes(reorder(country, wing, median), wing)) + geom_boxplot()

enter image description here

How can I order the boxplots based on highest-lowest medians (left to right)?

like image 756
luciano Avatar asked May 18 '13 10:05

luciano


People also ask

How do you change the order of factors in R?

One way to change the level order is to use factor() on the factor and specify the order directly. In this example, the function ordered() could be used instead of factor() . Another way to change the order is to use relevel() to make a particular level first in the list.

How do I reorder my legend ggplot2?

You can use the following syntax to change the order of the items in a ggplot2 legend: scale_fill_discrete(breaks=c('item4', 'item2', 'item1', 'item3', ...)

How do I reorder Boxplots in R?

To reorder the boxplot we will use reorder() function of ggplot2. By default, ggplot2 orders the groups in alphabetical order.


2 Answers

Because you did not make it an ordered factor. Try

ggplot(x, aes(reorder(country, wing, median, order=TRUE), wing)) + geom_boxplot()

enter image description here

like image 85
Roland Avatar answered Sep 30 '22 20:09

Roland


Your code should works fine. Probably you had some package loaded with a function that masked the base reorder function, or perhaps a user-defined reorder function, that doesn't work the same way.

You can check for such name-clashes with conflicts(). Detaching the package, rm(reorder), or restarting R and trying again without defining/attaching the conflicting definition will solve the problem.

like image 39
Gregor Thomas Avatar answered Sep 30 '22 21:09

Gregor Thomas