简体   繁体   English

使用 ggplot2 保持 geom_bar() 填充的顺序

[英]Maintain order of geom_bar() fill with ggplot2

I have a sediment core dataset that I would like to portray graphically with geom_bar() in ggplot2 and fill with a variable.我有一个沉积物核心数据集,我想用 ggplot2 中的 geom_bar() 以图形方式描绘并填充一个变量。 The fill variable alternates with every other level of fill, but with the new version (2.2.1) of ggplot2 I cannot maintain this fill pattern.填充变量与其他每个填充级别交替,但使用 ggplot2 的新版本 (2.2.1) 我无法保持这种填充模式。 This is discussed here but I cannot find a workable solution.这在这里讨论但我找不到可行的解决方案。

library(ggplot2)
site<-c(rep('a',14),rep('z',8))
sedcore<-1
fill<-c("y","n","y","n","y","n","y","n","y","n","y","n","y","n","y","n","y","n","y","n","y","n")
df <- data.frame(cbind(site,sedcore,fill))

ggplot(df, aes(x=site, y=sedcore, fill=fill)) + geom_bar(position="stack",stat="identity",colour="black",size=0.35)

订单未维护

The newest version of ggplot does NOT maintain the order of the dataframe ggplot 的最新版本不维护数据帧的顺序

If I load ggplot2 version 2.1 the order of the dataframe is maintained:如果我加载 ggplot2 2.1 版,数据帧的顺序将保持不变:

library(devtools)
install_version("ggplot2", version = "2.1.0", repos = "http://cran.us.r-project.org") 
library(ggplot2)

ggplot(df, aes(x=site, y=sedcore, fill=fill)) + geom_bar(position="stack",stat="identity",colour="black",size=0.35)

The same exact code now maintains the order:相同的代码现在保持顺序: 维持秩序

Please advise on how to maintain order from dataframe.请告知如何从数据框中维护订单。 I have tried reordering my dataframe and different position and stack terms, but cannot figure this out.我试过重新排序我的数据框和不同的位置和堆栈术语,但无法弄清楚这一点。

Thanks in advance for any help.在此先感谢您的帮助。

The hacky solution as suggested by @thc @thc 建议的 hacky 解决方案

df$fill <- paste0(sprintf('%06d',1:nrow(df)), df$fill)
ggplot(df, aes(x=site, y=sedcore, fill=fill)) + geom_bar(position="stack",stat="identity",colour="black",size=0.35) + 
  scale_fill_manual(values=ifelse(grepl('y',df$fill), 'steelblue', 'red')) +
  guides(fill=FALSE)

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM