【问题标题】:Show percent of total on top of geom_bar in ggplot2 while showing counts on y axis在 ggplot2 的 geom_bar 顶部显示总数的百分比,同时在 y 轴上显示计数
【发布时间】:2018-11-04 07:46:11
【问题描述】:

我正在尝试使用 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)

我查看了其他答案,例如 How to add percentage or count labels above percentage bar plot?,但在这些示例中,y 轴和标签都显示百分比。我正在尝试在标签中显示 y 轴上的计数和百分比。

【问题讨论】:

标签: r ggplot2 dplyr tidyr tidyverse


【解决方案1】:

只需使用percent 作为标签。

iris %>% 
  group_by(Species) %>% 
  summarize(count = n()) %>% 
  mutate(percent = count/sum(count)) %>% 
  ggplot(aes(x=Species, y=count)) +
  geom_col() +
  geom_text(aes(label = paste0(round(100 * percent, 1), "%")), vjust = -0.25)

【讨论】:

    【解决方案2】:
    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))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-25
      • 1970-01-01
      相关资源
      最近更新 更多