[英]Show percent of total on top of geom_bar in ggplot2 while showing counts on y axis
我正在嘗試使用ggplot2創建條形圖,顯示y軸上的計數,但也顯示每個條形頂部的總計百分比。 我已經計算了總數的計數和百分比,但無法弄清楚如何在條形圖的頂部添加百分比。 我正在嘗試使用geom_text,但無法使其正常工作。
一個最小的例子:
iris %>%
group_by(Species) %>%
summarize(count = n()) %>%
mutate(percent = count/sum(count)) %>%
ggplot(aes(x=Species, y=count)) +
geom_bar(stat="identity") +
geom_text(aes(label = scales::percent(..prop..), y=..count..), stat= "count", vjust = -.5)
我看過其他答案,例如如何在百分比條形圖上方添加百分比或計數標簽? ,但在這些示例中,y軸和標簽都顯示百分比。 我試圖顯示y軸上的計數和標簽中的百分數。
library(dplyr)
library(ggplot2)
df1 = iris %>%
group_by(Species) %>%
summarize(count = n()) %>%
mutate(percent = count/sum(count))
ggplot(data = df1, aes(x = Species, y = count, label = paste0(round(percent,2),"%"))) +
geom_bar(stat="identity") +
geom_text(aes(y = count*1.1))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.