在geom_bar中留出一个空格,其中stat ='bin',position ='dodge'和零

时间:2014-01-15 13:32:02

标签: r ggplot2

假设我正在绘制一些这样的数据:

x = data.frame(cat=c('a', 'a', 'a', 'b', 'b'), type=c('x', 'x', 'y', 'x', 'x'))
ggplot(x, aes(cat, fill=type)) + geom_bar(stat='bin', position='dodge')

这给了我一个这样的情节:

enter image description here

然而,我想要的是所有的条都是相同的宽度,这样cat =='b'的空格就是蓝色条。我该怎么做?

2 个答案:

答案 0 :(得分:1)

这可能是一个潜在的解决方案,但我很乐意听到是否有更好的东西。

ggplot(as.data.frame(table(x$cat, x$type)), aes(Var1, Freq, fill=Var2)) + geom_bar(stat='identity', position='dodge')

答案 1 :(得分:0)

通过为stat_bin指定一些参数,没有简单的方法:跟随this question。 适合您案例的解决方案可能看起来像

require(reshape2)
x_dcast <- dcast(x, type ~ cat, fun.agg = length)
x_melt <- melt(x_dcast, id.vars = "type")
ggplot(x_melt, aes(variable, value, fill=type)) + 
  geom_bar(stat='identity', position='dodge')

请注意,您的答案可以稍微修改一下:

ggplot(as.data.frame(table(x)), aes(Var1, Freq, fill=Var2)) + 
  geom_bar(stat='identity', position='dodge')

您可以看到您的答案更加透明。无论如何,您都必须手动计算计数。

谈到“有点hacky” - 根据我的经验,这是R中非标准情况的常用方法。如果它完成了工作并且是可读的单行,为什么不呢?