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

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

问题描述

使用这个虚拟的data.frame

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

我尝试在顶部绘制类别蓝色".

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天全站免登陆