我正在绘制一个类别变量,而不是显示每个类别值的计数。
我正在寻找一种方法来让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个都给予:
错误:ggplot2不知道如何处理类因子的数据
的简单情况也会出现相同的错误
ggplot (data=mydataf, aes(levels(mydataf))) +
geom_bar()
这显然是关于ggplot如何与单个向量交互的。我摸不着头脑,在谷歌上搜索这个错误只得到一个结果。
从ggplot2 3.3版开始,我们可以访问方便的after_stat()函数。
我们可以做一些类似于@Andrew的回答,但是不用..语法:
# original example data
mydata <- c("aa", "bb", NULL, "bb", "cc", "aa", "aa", "aa", "ee", NULL, "cc")
# display percentages
library(ggplot2)
ggplot(mapping = aes(x = mydata,
y = after_stat(count/sum(count)))) +
geom_bar() +
scale_y_continuous(labels = scales::percent)
您可以在geom_和stat_函数的文档中找到所有可用的“计算变量”。例如,对于geom_bar(),可以访问count和prop变量。(请参阅计算变量的文档。)
关于你的NULL值的一个注释:当你创建向量时,它们被忽略(即你最终得到一个长度为9的向量,而不是11)。如果你真的想跟踪丢失的数据,你将不得不使用NA (ggplot2将把NA放在图的右端):
# use NA instead of NULL
mydata <- c("aa", "bb", NA, "bb", "cc", "aa", "aa", "aa", "ee", NA, "cc")
length(mydata)
#> [1] 11
# display percentages
library(ggplot2)
ggplot(mapping = aes(x = mydata,
y = after_stat(count/sum(count)))) +
geom_bar() +
scale_y_continuous(labels = scales::percent)
由reprex包于2021-02-09创建(v1.0.0)
(请注意,使用chr或fct数据不会对您的示例产生影响。)
从ggplot2 3.3版开始,我们可以访问方便的after_stat()函数。
我们可以做一些类似于@Andrew的回答,但是不用..语法:
# original example data
mydata <- c("aa", "bb", NULL, "bb", "cc", "aa", "aa", "aa", "ee", NULL, "cc")
# display percentages
library(ggplot2)
ggplot(mapping = aes(x = mydata,
y = after_stat(count/sum(count)))) +
geom_bar() +
scale_y_continuous(labels = scales::percent)
您可以在geom_和stat_函数的文档中找到所有可用的“计算变量”。例如,对于geom_bar(),可以访问count和prop变量。(请参阅计算变量的文档。)
关于你的NULL值的一个注释:当你创建向量时,它们被忽略(即你最终得到一个长度为9的向量,而不是11)。如果你真的想跟踪丢失的数据,你将不得不使用NA (ggplot2将把NA放在图的右端):
# use NA instead of NULL
mydata <- c("aa", "bb", NA, "bb", "cc", "aa", "aa", "aa", "ee", NA, "cc")
length(mydata)
#> [1] 11
# display percentages
library(ggplot2)
ggplot(mapping = aes(x = mydata,
y = after_stat(count/sum(count)))) +
geom_bar() +
scale_y_continuous(labels = scales::percent)
由reprex包于2021-02-09创建(v1.0.0)
(请注意,使用chr或fct数据不会对您的示例产生影响。)