在分组条形图上方添加计数和百分比

发布于 2025-01-10 21:14:52 字数 721 浏览 0 评论 0原文

如何在分组条形图中的每个条形上方添加计数和百分比(例如“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()))

enter image description here

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

淡淡の花香 2025-01-17 21:14:52

您可以执行以下操作:

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())

在此处输入图像描述

You can do:

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())

enter image description here

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文