12

我希望用来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, aes(x = name, y = count, group = sample)) + geom_bar(stat = "identity", position = "dodge")

在此处输入图像描述

但我无法让它避开其中一个分组(样本)并堆叠另一个分组(类型):

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

在此处输入图像描述

4

1 回答 1

18

一种解决方法是将sample和的交互name放在 x 轴上,然后调整 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"))

在此处输入图像描述

另一种解决方案是将分面用于namesample作为 x 值。

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

在此处输入图像描述

于 2014-01-28T15:42:43.130 回答