我正在尝试使用 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)
泰勒建议的更改:
+ theme(panel.margin = grid::unit(-1.25, "lines"))
关于r - ggplot2 - 带有堆栈和闪避的条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12715635/