使用图例在ggplot2中组织条形图

时间:2014-11-29 15:11:15

标签: r plot ggplot2 bar-chart

您好我正在尝试在ggplot2中订购条形码。

这是New数据框:

  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 

这是剧情剧本:

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

我想组织从较大的酒吧到较小的酒吧。我试过了:

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

然而,我收到了错误 有任何想法吗?非常感谢你。

1 个答案:

答案 0 :(得分:1)

这是一种方式:

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

基本上,我们会根据Mb列中的值重新排序因子级别。