Maintain order of geom_bar() fill with ggplot2

拜拜、爱过 提交于 2019-12-24 01:23:55

问题


I have a sediment core dataset that I would like to portray graphically with geom_bar() in ggplot2 and fill with a variable. 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. 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

If I load ggplot2 version 2.1 the order of the dataframe is maintained:

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.


回答1:


The hacky solution as suggested by @thc

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)



来源:https://stackoverflow.com/questions/42104085/maintain-order-of-geom-bar-fill-with-ggplot2

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!