![](/img/trans.png)
[英]Change count to percentage on faceted, filled geom_bar()/stat_count() plot in ggplot2 R
[英]Adding percentage labels to ggplot when using stat_count
由於某些原因,我似乎無法使用stat_count
向ggplot添加正確的比例標簽。 下面的代碼返回的標簽顯示所有類別的100%,即使我使用..prop..
我應該使用其他東西代替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
之前計算百分比來ggplot
(如下所示),但是我有很多代碼正在使用geom_bar
,如果要這樣做,則需要更改所有代碼。
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()
進行計算:
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.