本文介绍了ggplot2保留未使用的关卡barplot的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我想在我的条形图中绘制未使用的级别(即计数为0的级别),但未使用的级别会下降,我无法弄清楚如何保留它们。 $ b = pre $ df df $ type ggplot(df,aes(x = group,fill = type))+ geom_bar() 上面的例子中,我想看到C计数为0,但它是完全没有... ... 感谢您的帮助 Ulrik 编辑: 这就是我想要的 df1 df $ type df1 $ type 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()计算频率然后绘图 解决方案您需要在这两个比例(fill和x)上设置drop = FALSE,如下所示: df df1 df $ type< ; - 因子(df $ type,levels = c(A,B,C)) df1 $ type plt plt1 < - ggplot(df1,aes(x = type,fill = type))+ geom_bar(position ='dodge')+ scale_fill_discrete(drop = FALSE)+ scale_x_discrete(drop = FALSE) 编辑: 我非常肯定这是有效的。忘了将x改为键入而不是组和位置='闪避'!只需粘贴并测试。 stat_bin处理零计数的分箱。查看文档。 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 themdf <- 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()In the above example, I want to see C plotted with a count of 0, but it is completely absent...Thanks for any helpUlrikEdit:This does what I wantdf <- 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")Guess the solution is to calculate the frequencies using table() and then plot 解决方案 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)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. 这篇关于ggplot2保留未使用的关卡barplot的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-20 12:24