保持未使用的级别

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

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绘制,但是它完全不存在..。

谢谢你的帮助 乌尔里克

编辑:

这就是我想要的

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 ()计算频率,然后绘图

48576 次浏览

这是你想要的吗?

ggplot(df, aes(x=type)) + geom_bar() + scale_x_discrete(drop=FALSE)

enter image description here

你需要像这样设置 drop = FALSE 在两个刻度(fill 和 x)上:

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)

Edit:

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.

降级不起作用。在第一个示例中降级

library(ggplot2)


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(position="dodge") + scale_x_discrete(drop=FALSE) + scale_fill_discrete(drop=FALSE)

结果如下:

enter image description here

第二个例子中的解决方案是手工计算频率:

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


df$plot = "A"
df1$plot = "B"


df <- rbind(df, df1)


ggplot(df, aes(x=group, y=Freq, fill=type)) + geom_bar(position="dodge", stat="identity") + facet_wrap( ~ plot, scales="free")

结果是:

enter image description here

最后一个是信息量最大的,因为那里的类别 count = 0占据了空间

也可以使用“ scale _ fill _ color” 例如:

plt <- ggplot(df, aes(x=type, fill=type)) + geom_bar(position='dodge') + scale_x_discrete(drop=FALSE)+
scale_fill_manual(
values = c(
"#ff6666",
"#cc9900",
"#cc9900"
),drop=FALSE)