我希望用于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")
一个解决办法是把互动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"))
另一种解决方案是将构面用于name
和sample
作为x值。
ggplot(df,aes(x=sample,y=count,fill=type))+
geom_bar(stat = "identity",color="white")+
facet_wrap(~name,nrow=1)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句