在ggplot中生成成对堆积条形图(仅在某些变量上使用position_dodge) [英] Generate paired stacked bar charts in ggplot (using position_dodge only on some variables)

查看:43
本文介绍了在ggplot中生成成对堆积条形图(仅在某些变量上使用position_dodge)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望使用 ggplot2 生成一组成对的堆叠条形,就像这样:

I'm hoping to use ggplot2 to generate a set of stacked bars in pairs, much like this:

使用以下示例数据:

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 轴代表树的名称,每个树种有两个条形:一个条形代表样本一,一个条形代表样本二.然后每个条的颜色应该由类型决定.

I would want the x-axis to represent the name of the tree, with two bars per tree species: one bar for sample one and one bar for sample two. Then the colors of each bar should be determined by type.

以下代码按类型生成带有颜色的堆叠条:

The following code generates the stacked bar with colors by type:

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

并且以下代码通过示例生成躲避条:

And the following code generates the dodged bars by sample:

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

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

But I can't get it to dodge one of the groupings (sample) and stack the other grouping (type):

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

推荐答案

一种解决方法是将 samplename 的交互放在 x 轴上,然后调整标签对于 x 轴.问题是条形没有彼此靠近.

One workaround would be to put interaction of sample and name on x axis and then adjust the labels for the x axis. Problem is that bars are not put close to each other.

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 值.

Another solution is to use facets for name and sample as x values.

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

这篇关于在ggplot中生成成对堆积条形图(仅在某些变量上使用position_dodge)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆