我希望用它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")
一种解决方法是在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"))
另一种解决方案是使用facet name
和sample
x值.
ggplot(df,aes(x=sample,y=count,fill=type))+ geom_bar(stat = "identity",color="white")+ facet_wrap(~name,nrow=1)