如何在分組條形圖中的每個條形上方同時添加計數和百分比,例如“11 (2%)”?我只能使用下面的代碼來計算百分比。謝謝!
library(dplyr)
library(scales)
library(ggplot2)
print(mtcars %>%
count(cyl = factor(cyl), gear = factor(gear)) %>%
mutate(pct = prop.table(n)) %>%
ggplot(aes(x = cyl, y = pct, fill = gear, label = scales::percent(pct)))
geom_col(position = "dodge")
geom_text(position = position_dodge(width = .9), vjust = -0.5, size = 3)
scale_y_continuous(labels = scales::percent)
theme(axis.title.y = element_blank(),
axis.text.y = element_blank()))

uj5u.com熱心網友回復:
你可以做:
library(dplyr)
library(scales)
library(ggplot2)
mtcars %>%
count(cyl = factor(cyl), gear = factor(gear)) %>%
mutate(pct = prop.table(n)) %>%
ggplot(aes(x = cyl, y = pct, fill = gear,
label = paste0(n, "\n(", scales::percent(pct), ")")))
geom_col(position = "dodge")
geom_text(position = position_dodge(width = .9), vjust = -0.5, size = 3)
scale_y_continuous(labels = scales::percent, limits = c(0, 0.5))
theme(axis.title.y = element_blank(),
axis.text.y = element_blank())

轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/435711.html
上一篇:如何單獨繪制geom_point加上geom_point和position_dodge
下一篇:基于三個變數創建箱線圖
