4

I always seem to come across this problem when plotting with ggplot2 and trying to reorder the factors according to a numeric variable in the data.frame.

structure(list(Team = structure(1:32, .Label = c("ARI", "ATL", 
"BAL", "BUF", "CAR", "CHI", "CIN", "CLE", "DAL", "DEN", "DET", 
"GB", "HOU", "IND", "JAC", "KC", "MIA", "MIN", "NE", "NO", "NYG", 
"NYJ", "OAK", "PHI", "PIT", "SD", "SEA", "SF", "STL", "TB", "TEN", 
"WAS"), class = "factor"), Fans = c(49L, 145L, 175L, 75L, 104L, 
167L, 101L, 147L, 157L, 304L, 112L, 338L, 200L, 118L, 37L, 60L, 
65L, 225L, 371L, 97L, 163L, 87L, 84L, 102L, 111L, 85L, 422L, 
311L, 63L, 56L, 49L, 271L)), .Names = c("Team", "Fans"), row.names = c(NA, 
-32L), class = "data.frame")

This does not reorder the teams by # of fans:

ggplot(total.fans, aes(x=reorder(Team, Fans), y=Fans)) + geom_bar()

And this transform call doesn't change the data either:

transform(total.fans, variable=reorder(Team, -Fans))

What am I missing?

tcash21
  • 4,880
  • 4
  • 32
  • 39

2 Answers2

5

It works for me with ggplot2 0.9.3, although I get warnings: I think you want

ggplot(total.fans, aes(x=reorder(Team, Fans),y=Fans)) + 
   geom_bar(stat="identity")

enter image description here

(Posting rather than commenting so I can show the plot ...)

Ben Bolker
  • 211,554
  • 25
  • 370
  • 453
  • I just upgraded from ggplot 0.2.1 to 0.9.3 and I receive this error when trying ggplot(total.fans, aes(x=reorder(Team, Fans), y=Fans)) + geom_bar() Error in rename(x, .base_to_ggplot, warn_missing = FALSE) : could not find function "revalue" – tcash21 Dec 25 '12 at 20:17
  • 2
    make sure you've updated the `plyr` package as well (see http://blog.rstudio.org/2012/12/06/ggplot2-plyr-release/ ) – Ben Bolker Dec 25 '12 at 20:28
3

You can reorder your factor also outside the ggplot() call with function factor() and then use ggplot().

total.fans$Team <- factor(total.fans$Team , levels = total.fans[order(total.fans$Fans), 1])
ggplot(total.fans, aes(x=Team, y=Fans)) + geom_bar(stat="identity")
Didzis Elferts
  • 95,661
  • 14
  • 264
  • 201
  • Thanks this worked, I'll accept as solution, but still trying to figure out what went wrong on the other answer. – tcash21 Dec 25 '12 at 20:17