我想创建使用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=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)
随着泰勒的建议的修改:
你可以得到最接近的是周围绘制的边框dodged
条,强调了堆叠type
值。
ggplot(df, aes(treatment, total, fill = year)) +
geom_bar(stat="identity", position="dodge", color="black")
可以使用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)。