首页 文章

使用ggplot2维护geom_bar()的顺序

提问于
浏览
2

我有一个沉积物核心数据集,我想用ggplot2中的geom_bar()以图形方式描绘并填充变量 . 填充变量与每个其他填充级别交替,但是对于ggplot2的新版本(2.2.1),我无法维护此填充模式 . 这是讨论here但我找不到可行的解决方案 .

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

最新版本的ggplot不保持数据帧的顺序

如果我加载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)

相同的代码现在维护顺序:
Order maintained

请告知如何从数据框维护订单 . 我尝试重新排序我的数据帧和不同的位置和堆栈条款,但无法弄清楚这一点 .

在此先感谢您的帮助 .

1 回答

  • 1

    @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)
    

    enter image description here

相关问题