简体   繁体   中英

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. 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.

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)

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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