ggplot2-带有堆栈和闪避的条形图

我试图创建一个条形图,使用ggplot2一个变量在其中堆叠而另一个变量在其中躲避。


这是一个示例数据集:


df=data.frame(

  year=rep(c("2010","2011"),each=4),

  treatment=rep(c("Impact","Control")),

  type=rep(c("Phylum1","Phylum2"),each=2),

  total=sample(1:100,8))

我想创建一个条形图,其中x=treatment,y=total堆叠变量为type和躲避变量为year。我当然可以做一个或另一个:


ggplot(df,aes(y=total,x=treatment,fill=type))+geom_bar(position="dodge",stat="identity")


ggplot(df,aes(y=total,x=treatment,fill=year))+geom_bar(position="dodge",stat="identity")

但不是两者!感谢任何可以提供建议的人。


泛舟湖上清波郎朗
浏览 756回答 3
3回答

牛魔王的故事

这是使用构面而不是躲避的另一种选择:ggplot(df, aes(x = year, y = total, fill = type)) +    geom_bar(position = "stack", stat = "identity") +    facet_wrap( ~ treatment)根据泰勒的建议更改: + theme(panel.margin = grid::unit(-1.25, "lines"))

料青山看我应如是

最接近的方法是在dodged条形图周围绘制边框以突出显示堆积的type值。ggplot(df, aes(treatment, total, fill = year)) + geom_bar(stat="identity", position="dodge", color="black")
打开App,查看更多内容
随时随地看视频慕课网APP