我希望使用ggplot2成对生成一组堆叠的条形图,如下所示:
使用以下示例数据:
df <- expand.grid(name = c("oak","birch","cedar"),sample = c("one","two"),type = c("sapling","adult","dead")) df$count <- sample(5:200,size = nrow(df),replace = T)
我希望x轴代表树的名称,每种树种有两个条形:样品一个条形,样品条形一个条形条纹.然后每个条的颜色应按类型确定.
ggplot(df,aes(x = name,y = count,fill = type)) + geom_bar(stat = "identity")
ggplot(df,group = sample)) + geom_bar(stat = "identity",position = "dodge")
但我不能让它躲避其中一个分组(样本)并堆叠其他分组(类型):
ggplot(df,fill = type,position = "dodge")
解决方法
一种解决方法是将样本和名称的交互放在x轴上,然后调整x轴的标签.问题是酒吧不会彼此靠近.
ggplot(df,aes(x = as.numeric(interaction(sample,name)),fill = type)) + geom_bar(stat = "identity",color="white") + scale_x_continuous(breaks=c(1.5,3.5,5.5),labels=c("oak","cedar"))
ggplot(df,aes(x=sample,y=count,fill=type))+ geom_bar(stat = "identity",color="white")+ facet_wrap(~name,nrow=1)