如何使用ggplot2上的标识控制堆积条形图的排序 [英] How to control ordering of stacked bar chart using identity on ggplot2

查看:1244
本文介绍了如何使用ggplot2上的标识控制堆积条形图的排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用这个虚拟 data.frame

ts <- data.frame(x=1:3, y=c("blue", "white", "white"), z=c("one", "one", "two"))

我尝试在类别blue的顶部绘图。

I try and plot with category "blue" on top.

ggplot(ts, aes(z, x, fill=factor(y, levels=c("blue","white" )))) + geom_bar(stat = "identity")

给我白色的顶部。和

ggplot(ts, aes(z, x, fill=factor(y, levels=c("white", "blue")))) + geom_bar(stat = "identity")

颠倒了颜色,但仍然让我白在上面。我怎么能得到蓝色顶部?

reverses the colors, but still gives me "white" on top. How can I get "blue" on top?

推荐答案

以前我一直在努力解决同样的问题。看起来,ggplot根据它们在数据框中的外观来堆叠条形图。因此,解决您的问题的方法是按照您希望它出现在图例中的相反顺序填充因子对数据进行排序:数据框顶部的底部项目和底部的顶部项目:

I've struggled with the same issue before. It appears that ggplot stacks the bars based on their appearance in the dataframe. So the solution to your problem is to sort your data by the fill factor in the reverse order you want it to appear in the legend: bottom item on top of the dataframe, and top item on bottom:

ggplot(ts[order(ts$y, decreasing = T),],
       aes(z, x, fill=factor(y, levels=c("blue","white" )))) + 
  geom_bar(stat = "identity")

使用示例数据,我创建了三个具有不同数据框顺序的图表,我认为更多的填充变量会使事情变得更清晰一些。

Using sample data, I created three plots with different orderings of the dataframe, I thought that more fill-variables would make things a bit clearer.

set.seed(123)
library(gridExtra)
df <- data.frame(x=rep(c(1,2),each=5),
                 fill_var=rep(LETTERS[1:5], 2),
                 y=1)
#original order   
p1 <- ggplot(df, aes(x=x,y=y,fill=fill_var))+
  geom_bar(stat="identity") + labs(title="Original dataframe")


#random order
p2 <- ggplot(df[sample(1:10),],aes(x=x,y=y,fill=fill_var))+
  geom_bar(stat="identity") + labs(title="Random order")
#legend checks out, sequence wird

#reverse order
p3 <- ggplot(df[order(df$fill_var,decreasing=T),],
             aes(x=x,y=y,fill=fill_var))+
  geom_bar(stat="identity") + labs(title="Reverse sort by fill")

plots <- list(p1,p2,p3)

do.call(grid.arrange,plots)

这篇关于如何使用ggplot2上的标识控制堆积条形图的排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆