2
votes

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)

Order not maintained

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: Order maintained

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
One hack-y solution would be to create another factor level for each layer in your barplot, and then use scale_fill_manual to define the colors for each factor level. However, I think the first output is preferable in general, since data in ggplot is sorted by factor.thc

1 Answers

1
votes

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)

enter image description here