使用stat_count时将百分比标签添加到ggplot [英] Adding percentage labels to ggplot when using stat_count
问题描述
由于某种原因,我似乎无法使用 stat_count
向ggplot添加正确的比例标签.即使我使用的是 .. prop ..
,下面的代码也会返回所有类别均显示100%的标签.我是否应该使用其他东西代替 stat_count
?
For some reason, I can't seem to be able to add correct proportion labels to a ggplot by using stat_count
. The code below returns labels that display 100% for all categories, even though I'm using ..prop..
. Should I use something else instead of stat_count
?
library(tidyverse)
diamonds %>%
ggplot(aes(color, fill=cut)) +
geom_bar(position = 'fill') +
stat_count(aes(label= scales::percent(..prop..)),
geom = 'text', position = position_fill(vjust = 0.5))
我知道这也可以通过在将数据输入到 ggplot
(如下所示)之前计算百分比来实现,但是我有很多使用 geom_bar
的代码如果我要这样做,就需要更改所有内容.
I know this can also be accomplished by calculating the percentage before feeding the data to ggplot
(like below) but I have quite a bit of code which is using geom_bar
and I would need to change all of it if I were to do it this way.
diamonds %>%
count(color, cut) %>%
group_by(color) %>%
mutate(pct=n/sum(n)) %>%
ggplot(aes(color, pct, fill=cut)) +
geom_col(position = 'fill') +
geom_text(aes(label=scales::percent(pct)), position = position_fill(vjust=0.5))
推荐答案
如果您不想更改 geom_bar
geom_label()中进行计算>部分:
You can do the calculations within geom_label()
, if you don't want to change the geom_bar
part:
diamonds %>%
ggplot(aes(color, fill=cut)) +
geom_bar(position = 'fill') +
geom_text(data = . %>%
group_by(color, cut) %>%
tally() %>%
mutate(p = n / sum(n)) %>%
ungroup(),
aes(y = p, label = scales::percent(p)),
position = position_stack(vjust = 0.5),
show.legend = FALSE)
这篇关于使用stat_count时将百分比标签添加到ggplot的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!