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