ggplot2 - 带有堆栈和闪避的条形图 [英] ggplot2 - bar plot with both stack and dodge

查看:40
本文介绍了ggplot2 - 带有堆栈和闪避的条形图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 ggplot2 创建一个条形图,其中我通过一个变量进行堆叠并通过另一个变量进行躲避.

I am trying to create a barplot using ggplot2 where I am stacking by one variable and dodging by another.

这是一个示例数据集:

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=treatmenty=total,堆叠变量为type,躲避变量为.我当然可以选择其中之一:

I would like to create a barplot where x=treatment, y=total, the stacked variable is type and the dodged variable is year. Of course I can do one or the other:

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

但不能两者兼而有之!感谢任何可以提供建议的人.

But not both! Thanks to anyone who can provide advice.

推荐答案

这是使用分面代替闪避的另一种选择:

Here's an alternative take using faceting instead of dodging:

ggplot(df, aes(x = year, y = total, fill = type)) +
    geom_bar(position = "stack", stat = "identity") +
    facet_wrap( ~ treatment)

根据 Tyler 的建议更改:+ theme(panel.margin = grid::unit(-1.25, "lines"))

With Tyler's suggested change: + theme(panel.margin = grid::unit(-1.25, "lines"))

这篇关于ggplot2 - 带有堆栈和闪避的条形图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆