我正在绘制一个分类变量,而不是显示每个类别值的计数。
我正在寻找一种方法让 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
,但正确使用stat_bin仍然使我困扰。
我还尝试了以下四种方法:
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();
但是所有4个都会给出以下结果:
相同的错误也会出现在简单情况下的代码中。Error: ggplot2 doesn't know how to deal with data of class factor
ggplot (data=mydataf, aes(levels(mydataf))) +
geom_bar()
很明显,这是关于ggplot
如何与单个向量交互的问题。我正在思考,谷歌搜索该错误只返回了一个结果。