user3091668
user3091668

Reputation: 2310

Organize bars in ggplot2 with legend

Hello I am trying to order the bars in ggplot2.

This is the New dataframe:

  Mb       category       reason
585.79       All           Known 
170.55       All            New 
126.67    Overlapped        New 
252.29    Overlapped       Known 
10.95     Reciprocal        New 
37.89     Reciprocal       Known 
40.27      Absolute         New 
118.58     Absolute        Known 

This is the plot script:

ggplot(New, aes(factor(reason), Mb, fill = category)) + geom_bar(stat="identity" , position = "dodge") + scale_fill_brewer(palette = "Set1") + theme(axis.title.x = element_blank()) + theme(text = element_text(size=15)) + theme(legend.title = element_blank())

enter image description here

I would like to organize the bars from the bigger to the smaller bar. I had tried:

ggplot(New, aes(factor(reason), Mb, fill = category)) + 
  geom_bar(stat="identity" , position = "dodge") + 
  scale_fill_brewer(palette = "Set1") + theme(axis.title.x = element_blank()) +
  theme(text = element_text(size=15)) + theme(legend.title = element_blank()) +
  scale_x_discrete(limits=c("All","Overlapped", "Absolute", "Reciprocal"))

However, I got the error.
Any ideas? Thank you very much.

Upvotes: 1

Views: 286

Answers (1)

jlhoward
jlhoward

Reputation: 59385

Here is one way:

library(ggplot2)
New$category <- with(New,reorder(category,Mb,function(x)-max(x)))

ggplot(New, aes(factor(reason), Mb, fill = category)) + 
  geom_bar(stat="identity" , position = "dodge") + 
  scale_fill_brewer(palette = "Set1") + 
  theme(axis.title.x = element_blank()) + 
  theme(text = element_text(size=15)) + 
  theme(legend.title = element_blank())

Basically, we're reordering the factor levels based on the values in the Mb column.

Upvotes: 1

Related Questions