Reputation: 73
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.
Upvotes: 2
Views: 519
Reputation: 23101
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)
Upvotes: 1