开发者

ggplot2 position='dodge' producing bars that are too wide

I'm interested in producing a histogram with position='dodge' and fill=some factor (i.e. 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 technic开发者_运维百科ally 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)

ggplot2 position='dodge' producing bars that are too wide

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜