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

标签 r 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")

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

最佳答案

这是使用刻面而不是躲避的替代方法:

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

enter image description here

泰勒建议的更改:+ theme(panel.margin = grid::unit(-1.25, "lines"))
enter image description here

关于r - ggplot2 - 带有堆栈和闪避的条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12715635/

相关文章:

r - 根据开始和停止时间计算每天的分钟数

r - 如何将Stata marksample转换为R语言?

Rcpp Armadillo : failing to install on CentOS

r - 使用 ggplot 在饼图中心打洞

r - ggplot2 分组条形图中变量的总和

r - 使用effects包比较涉及来自ggplot2与base R的连续变量的交互效应图

r - 错误: Aesthetics must be either length 1 or the same as the data (4)

r - 在 tidyr::gather 中使用多个键

r - 如何使用 R 创建新的 ID 列

r - 如何在我的散点图上创建一条更平滑的线而不是多条?