在ggplot中生成成对的堆积条形图(仅对某些变量使用position_dodge)

我希望使用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"))

另一种解决方案是将名称和样本的构面用作x值.

ggplot(df,aes(x=sample,y=count,fill=type))+
  geom_bar(stat = "identity",color="white")+
  facet_wrap(~name,nrow=1)

相关文章

Css3如何实现鼠标移上变长特效?(图文+视频)
css3怎么实现鼠标悬停图片时缓慢变大效果?(图文+视频)
jquery如何实现点击网页回到顶部效果?(图文+视频)
css3边框阴影效果怎么做?(图文+视频)
css怎么实现圆角边框和圆形效果?(图文+视频教程)
Css3如何实现旋转移动动画特效