ggplot2 - 在堆积条形图中翻转级别的顺序

时间:2012-10-22 07:03:12

标签: r ggplot2

此代码相当小,应该可以调整为解决方案。

blah <- data.frame(X1=c("Decrease Risk","Don't Know","Increase Risk","No Effect","Decrease Risk","Don't Know","Increase Risk","No Effect"),
                   X2=c("Red Meat","Red Meat","Red Meat","Red Meat","Red Meat","Red Meat","Red Meat","Red Meat"),
                   value=c(1.98,31.19,64.38,2.43,4.65,24.55,35.88,34.90),
                   status=c("Case","Case","Case","Case","Control","Control","Control","Control")
                   )

ggplot(blah, aes(X2, value, fill=X1)) + geom_bar() + coord_flip() + facet_wrap(~status) + 
    labs(x="Perceived Risk Factors", y="Percentage (%)", tilte="Some Title", fill="Responses")

enter image description here

我想要的是,右边的“控件”具有“响应”级别的顺序。关键是控制紫色在内部,然后是蓝色,然后在外面是绿色,粉红色。在这样的情节中这样做是很常见的,我可以想办法做一些涉及一些相当脏的重复变量和改变有序因子水平,但是认为有人可能有一个优雅的解决方案/想法?

1 个答案:

答案 0 :(得分:3)

这是一种使用订单美学的微妙方法。

ggplot(blah, aes(X2, value, fill = X1, 
  order = (3-as.numeric(status)*2) * as.numeric(X1))) + 
geom_bar() + coord_flip() + facet_wrap(~status) + 
labs(x="Perceived Risk Factors", y="Percentage (%)", title="Some Title", 
  fill="Responses")

enter image description here

这并不理想,因为当有两个以上的方面时,它并不容易概括。