简体   繁体   English

ggplot2 position ='dodge'生成太宽的条形图

[英]ggplot2 position='dodge' producing bars that are too wide

I'm interested in producing a histogram with position='dodge' and fill=some factor (ie side-by-side bars for different subgroups within each bar/group), but ggplot2 gives me something like the first plot here , which has a rightmost bar that's too wide and reserves no space for the empty group, which I would like. 我有兴趣生成一个position ='dodge'和fill =某个因子的直方图(即每个bar / group中不同子组的并排条),但是ggplot2给了我类似于这里的第一个图 ,它有一个最右边的酒吧太宽,没有为空组保留空间,我想要。

Here's a simple case: 这是一个简单的案例:

df = data.frame(a=c('o','x','o','o'), b=c('a','b','a','b'))
qplot(a, data=df, fill=b, position='dodge')

From ggplot geom_bar - bars too wide I got this idea, and while it technically produces a bar of the same width, but preserves no space for the empty group: ggplot geom_bar - 条形太宽我得到了这个想法,虽然它在技术上产生了一个相同宽度的条,但保留空组的空间:

ggplot(df, aes(x=a, fill=a))+
geom_bar(aes(y=..count../sum(..count..))) + 
facet_grid(~b,scales="free",space="free")

How do I achieve what I want? 我如何实现我想要的目标? Thanks in advance. 提前致谢。

The default options in ggplot produces what I think you describe. ggplot的默认选项产生了我认为你描述的内容。 The scales="free" and space="free" options does the opposite of what you want, so simply remove these from the code. scales="free"space="free"选项与你想要的相反,所以只需从代码中删除它们。 Also, the default stat for geom_bar is to aggregate by counting, so you don't have to specify your stat explicitly. 此外, geom_bar的默认stat geom_bar是通过计数进行聚合,因此您无需明确指定您的统计信息。

ggplot(df, aes(x=a, fill=a)) + geom_bar() + facet_grid(~b)

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM