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

can*_*ine 9 position r ggplot2 geom-bar

我希望用它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)
Run Code Online (Sandbox Code Playgroud)

我希望x轴代表树的名称,每种树种有两个条形:样品一个条形,样品条形一个条形条纹.然后每个条的颜色应由类型确定.

以下代码按类型生成带颜色的堆积条:

ggplot(df, aes(x = name, y = count, fill = type)) + geom_bar(stat = "identity")
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

以下代码通过示例生成躲避条:

ggplot(df, aes(x = name, y = count, group = sample)) + geom_bar(stat = "identity", position = "dodge")
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

但我不能让它躲避其中一个分组(样本)并堆叠其他分组(类型):

ggplot(df, aes(x = name, y = count, fill = type, group = sample)) + geom_bar(stat = "identity", position = "dodge")
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

Did*_*rts 12

一种解决方法是在x轴上放置sample和交互,name然后调整x轴的标签.问题是酒吧没有彼此靠近.

ggplot(df, aes(x = as.numeric(interaction(sample,name)), y = count, fill = type)) + 
  geom_bar(stat = "identity",color="white") +
  scale_x_continuous(breaks=c(1.5,3.5,5.5),labels=c("oak","birch","cedar"))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

另一种解决方案是使用facet namesamplex值.

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

在此输入图像描述