内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用
我正在绘制一个分类变量,而不是显示每个类别值的计数。
我想找个办法ggplot
若要显示该类别中值的百分比,请执行以下操作。当然,可以用计算出的百分比和绘图来创建另一个变量,但是我必须做几十次,我希望在一个命令中实现这一点。
我在做这样的实验
qplot(mydataf) + stat_bin(aes(n = nrow(mydataf), y = ..count../n)) + scale_y_continuous(formatter = "percent")
但我一定是不正确地使用它,因为我有错误。
为了方便地再现设置,下面是一个简化的示例:
mydata <- c ("aa", "bb", null, "bb", "cc", "aa", "aa", "aa", "ee", null, "cc"); mydataf <- factor(mydata); qplot (mydataf); #this shows the count, I'm looking to see % displayed.
在实际情况下,我可能会用ggplot
而不是qplot
,但是正确的使用方式统计_垃圾箱我还是躲不起来。
我也尝试过以下四种方法:
ggplot(mydataf, aes(y = (..count..)/sum(..count..))) + scale_y_continuous(formatter = 'percent'); ggplot(mydataf, aes(y = (..count..)/sum(..count..))) + scale_y_continuous(formatter = 'percent') + geom_bar(); ggplot(mydataf, aes(x = levels(mydataf), y = (..count..)/sum(..count..))) + scale_y_continuous(formatter = 'percent'); ggplot(mydataf, aes(x = levels(mydataf), y = (..count..)/sum(..count..))) + scale_y_continuous(formatter = 'percent') + geom_bar();
但这四项都提供了:
Error: ggplot2 doesn't know how to deal with data of class factor
简单的情况下,也会出现相同的错误。
ggplot (data=mydataf, aes(levels(mydataf))) + geom_bar()
总结上述评论中的讨论:
require(ggplot2) require(scales) p <- ggplot(mydataf, aes(x = foo)) + geom_bar(aes(y = (..count..)/sum(..count..))) + ## version 3.0.9 # scale_y_continuous(labels = percent_format()) ## version 3.1.0 scale_y_continuous(labels=percent)
下面是一个可复制的示例mtcars
:
ggplot(mtcars, aes(x = factor(hp))) + geom_bar(aes(y = (..count..)/sum(..count..))) + ## scale_y_continuous(labels = percent_format()) #version 3.0.9 scale_y_continuous(labels = percent) #version 3.1.0
备注:如果hp
不设置为一个因素,ggplots返回:
这个修改后的代码应该可以工作。
p = ggplot(mydataf, aes(x = foo)) + geom_bar(aes(y = (..count..)/sum(..count..))) + scale_y_continuous(formatter = 'percent')
如果您的数据具有nas,并且不希望它们包含在绘图中,则将na.omit(Mydataf)作为参数传递给ggart。