2

How do I change the order of bars for a barplot generated from a data frame?

I tried code from here: R - ordering in boxplot but it seems to only work for boxplots, e.g.

foo=data.frame(a=c(1,2,3),b=c("a","b","c"))
barplot(height=foo$a,names.arg=foo$b)
boxplot(foo$a~foo$b)
foo$c=factor(foo$b,c("c","b","a"))
barplot(height=foo$a,names.arg=foo$c)
boxplot(foo$a~foo$c)
Community
  • 1
  • 1
user1521655
  • 486
  • 3
  • 17
  • 1
    It's not that it only works for boxplots, it's that the two functions use different criteria for determining the order of the x-axis. Boxplot does what most functions do and takes the factor "c" as the x-axis. When you do this, the values will print out according to the order of the levels of the factor. Note that you're just passing a vector of heights to `barplot` so those heights print in whatever order you pass them in. `names.arg` only deals with how they are named, not the order they are drawn. There is nothing in the `heights` parameter is aware of the factor "c". – MrFlick Jun 16 '14 at 18:11
  • Hmm... this seems quite obvious now that you mention it. Does `barplot` simply not recognize data frames and similar structures? – user1521655 Jun 16 '14 at 19:31
  • 1
    Alas it does not. It does not have a formula interface as most other plotting functions do. – MrFlick Jun 16 '14 at 19:34

1 Answers1

2

This worked for me

foo$c=factor(foo$b, levels = c("c","b","a"))
foo <- foo[order(foo$c), ]
barplot(height=foo$a,names.arg=foo$c)
r.bot
  • 5,309
  • 1
  • 34
  • 45
  • This answer might do. I'm still curious as to whether there's a way of doing this without editing the data frame (or generating a new data frame), so I'm going to leave the question open for a bit. – user1521655 Jun 16 '14 at 19:34
  • Ok, thinking about this more, I realize that there's probably not a better way of doing this than either your suggestion or using your subscript-indexing method for each input vector. Thanks for your help! – user1521655 Jun 16 '14 at 19:47