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