繁体   English   中英

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

[英]Leaving a space in geom_bar with stat='bin', position='dodge' and zeroes

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

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')

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

在此输入图像描述

但是,我想要的是所有的条都是相同的宽度,这样就有一个空的空间用于cat =='b',蓝色条就是这样。 我该怎么做呢?

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

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

通过为stat_bin指定一些参数,没有简单的方法:按照这个问题 适合您的情况的解决方案可能看起来像

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中非标准情况的常用方法。如果它能完成工作并且是可读的单行,为什么不呢?

暂无
暂无

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

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