ggplot2中的geom_bar宽度 [英] geom_bar width in ggplot2

查看:991
本文介绍了ggplot2中的geom_bar宽度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用ggplot生成多面条形图。我有问题,下面的MWE会在底部生成图形。我希望它生成在两个面都具有相同宽度的条形。

I am generating faceted barchart with ggplot. I have the problem that the MWE below generates the graph at the bottom. I would like it to generate bars that have the same widths in both facets. How would I go about this?

library(ggplot2)

df = data.frame(x = as.factor(c(1, 2, 3, 1, 2)),
                y = c(2, 3, 4, 5, 6),
                g = c(1, 1, 1, 2, 2));

ggplot(df, aes(x = 1, y = y, fill = x)) +
  geom_bar(stat = "identity",
           position = "dodge") +
  facet_wrap(~ g);

推荐答案

不知道这是否是您需要的。使用 tidyr 包中的完整函数为缺少的因子水平创建占位符也可以使条宽相同在两个方面。

Not sure if this is what you need. Creating a place holder for the missing factor level using the complete function from tidyr package can also make the bar width the same at two facets. The downside is that the second plot is imblanced.

ggplot(tidyr::complete(df, x, g), aes(x = 1, y = y, fill = x)) +
       geom_bar(stat = "identity", position = "dodge") +
       facet_wrap(~ g);

这篇关于ggplot2中的geom_bar宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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