GGPLOT2 - 柱状图中与堆栈和闪避(ggplot2 - bar plot with both

2019-06-18 10:40发布

我想创建使用barplot 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))

我想创建一个barplot其中x=treatmenty=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")

但不能同时! 由于任何人谁可以提供咨询。

Answer 1:

下面是使用刻面,而不是回避的替代采取:

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

随着泰勒的建议的修改:



Answer 2:

你可以得到最接近的是周围绘制的边框dodged条,强调了堆叠type值。

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



Answer 3:

可以使用interaction(year, treatment)作为x轴可变作为替代dodge

library(tidyverse)

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)) %>% 
  mutate(x_label = factor(str_replace(interaction(year, treatment), '\\.', ' / '), ordered=TRUE))

ggplot(df, aes(x=x_label, y=total, fill=type)) +
  geom_bar(stat='identity') + labs(x='Year / Treatment')

由创建于2018年4月26日reprex包 (v0.2.0)。



文章来源: ggplot2 - bar plot with both stack and dodge
标签: r ggplot2