luciano
luciano

Reputation: 13792

Reorder() not correctly reordering a factor variable in ggplot

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)?

Upvotes: 17

Views: 12276

Answers (3)

Gregor Thomas
Gregor Thomas

Reputation: 145775

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.

Upvotes: 1

Hitesh Hits
Hitesh Hits

Reputation: 1

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

Upvotes: -1

Roland
Roland

Reputation: 132706

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

Upvotes: 6

Related Questions