不要丢弃零计数:躲避条形图 [英] Don't drop zero count: dodged barplot
问题描述
我在 ggplot2 中制作了一个躲避的条形图,一个分组的计数为零,我想显示.我记得不久前在 HERE 上看到了这个并想出了 scale_x_discrete(drop=F)
会起作用.它似乎不适用于躲避条.如何显示零计数?
I am making a dodged barplot in ggplot2 and one grouping has a zero count that I want to display. I remembered seeing this on HERE a while back and figured the scale_x_discrete(drop=F)
would work. It does not appear to work with dodged bars. How can I make the zero counts show?
例如(下面的代码)在下图中,type8~group4 没有示例.我仍然希望绘图显示零计数的空白空间,而不是消除条形.我该怎么做?
For instance, (code below) in the plot below, type8~group4 has no examples. I would still like the plot to display the empty space for the zero count instead of eliminating the bar. How can I do this?
mtcars2 <- data.frame(type=factor(mtcars$cyl),
group=factor(mtcars$gear))
m2 <- ggplot(mtcars2, aes(x=type , fill=group))
p2 <- m2 + geom_bar(colour="black", position="dodge") +
scale_x_discrete(drop=F)
p2
推荐答案
我所知道的唯一方法是预先计算计数并添加一个虚拟行:
The only way I know of is to pre-compute the counts and add a dummy row:
dat <- rbind(ddply(mtcars2,.(type,group),summarise,count = length(group)),c(8,4,NA))
ggplot(dat,aes(x = type,y = count,fill = group)) +
geom_bar(colour = "black",position = "dodge",stat = "identity")
我认为使用 stat_bin(drop = FALSE,geom = "bar",...)
会起作用,但显然它不起作用.
I thought that using stat_bin(drop = FALSE,geom = "bar",...)
instead would work, but apparently it does not.
这篇关于不要丢弃零计数:躲避条形图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!