简体   繁体   中英

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.

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(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. The scales="free" and space="free" options does the opposite of what you want, so simply remove these from the code. Also, the default stat for geom_bar is to aggregate by counting, so you don't have to specify your stat explicitly.

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

在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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