ggplot2保持未使用的级别barplot

时间:2012-05-31 13:14:15

标签: r ggplot2 legend levels

我想在我的条形图中绘制未使用的级别(即计数为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,但它完全没有...

感谢您的帮助 Ulrik

编辑:

这就是我想要的

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

4 个答案:

答案 0 :(得分:57)

这样做你想要的吗?

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

enter image description here

答案 1 :(得分:27)

您需要在两个比例(fill和x)上设置drop = FALSE,如下所示:

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更改为类型而不是组,并且位置=&#39;闪避&#39;!只需粘贴并测试即可。 stat_bin处理零计数的bin。检查docs

答案 2 :(得分:9)

删除级别不起作用。在第一个例子中删除级别

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

的类别占用

答案 3 :(得分:0)

你也可以使用&#34; scale_fill_color&#34; 例如:

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)