ggplot2 保持未使用的水平条形图 [英] ggplot2 keep unused levels barplot

查看:37
本文介绍了ggplot2 保持未使用的水平条形图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在条形图中绘制未使用的级别(即计数为 0 的级别),但是,未使用的级别已删除,我不知道如何保留它们

I want to plot unused levels (that is, levels where the count is 0) in my bar-plot, however, unused levels are dropped and I cannot figure out how to keep them

df <- data.frame(type=c("A", "A", "A", "B", "B"), group=rep("group1", 5))
df$type <- factor(df$type, levels=c("A","B", "C"))

ggplot(df, aes(x=group, fill=type)) + geom_bar()

在上面的例子中,我想看到 C 以 0 的计数绘制,但它完全不存在......

In the above example, I want to see C plotted with a count of 0, but it is completely absent...

感谢您的帮助乌尔里克

这就是我想要的

df <- data.frame(type=c("A", "A", "A", "B", "B"), group=rep("group1", 5))
df1 <- data.frame(type=c("A", "A", "A", "B", "B", "A", "A", "C", "B", "B"), group=c(rep("group1", 5),rep("group2", 5)))

df$type <- factor(df$type, levels=c("A","B", "C"))
df1$type <- factor(df1$type, levels=c("A","B", "C"))
df <- data.frame(table(df))

df1 <- data.frame(table(df1))

ggplot(df, aes(x=group, y=Freq, fill=type)) + geom_bar(position="dodge")
ggplot(df1, aes(x=group, y=Freq, fill=type)) + geom_bar(position="dodge")

猜测解决方案是使用 table() 计算频率,然后绘制

Guess the solution is to calculate the frequencies using table() and then plot

推荐答案

您需要像这样在两个尺度(填充和 x)上设置 drop=FALSE:

You need to set drop=FALSE on both scales (fill and x) like this:

library(ggplot2)
df <- data.frame(type=c("A", "A", "A", "B", "B"), group=rep("group1", 5))
df1 <- data.frame(type=c("A", "A", "A", "B", "B", "A", "A", "C", "B", "B"), group=c(rep("group1", 5),rep("group2", 5)))
df$type <- factor(df$type, levels=c("A","B", "C"))
df1$type <- factor(df1$type, levels=c("A","B", "C"))

plt <-  ggplot(df, aes(x=type, fill=type)) + 
          geom_bar(position='dodge') + 
          scale_fill_discrete(drop=FALSE) +
          scale_x_discrete(drop=FALSE)
plt1 <- ggplot(df1, aes(x=type, fill=type)) + 
          geom_bar(position='dodge') + 
          scale_fill_discrete(drop=FALSE) +
          scale_x_discrete(drop=FALSE)

我很确定这行得通.忘记将 x 更改为 type 而不是 group 和 position='dodge'!只需粘贴和测试.stat_bin 处理零计数的 bin.检查文档.

I'm pretty sure this works. Forgot to change x to type instead of group and the position='dodge'! Just paste and test. The stat_bin deals with bins with zero counts. Check the docs.

这篇关于ggplot2 保持未使用的水平条形图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆