在分组条形图上方添加计数和百分比
如何在分组条形图中的每个条形上方添加计数和百分比(例如“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()))
How can I add both count and percentage, something like "11 (2%)", above each bar in a grouped barplot? I can only do it for percentage using the code below. Thanks!
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()))
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以执行以下操作:
You can do: