简体   繁体   English

显示ggplot2中geom_bar顶部的总百分比,同时显示y轴上的计数

[英]Show percent of total on top of geom_bar in ggplot2 while showing counts on y axis

I'm trying to create a bar plot with ggplot2, showing counts on the y axis, but also the percents of total on top of each bar. 我正在尝试使用ggplot2创建条形图,显示y轴上的计数,但也显示每个条形顶部的总计百分比。 I've calculated the counts and percents of total, but can't figure out how to add the percents total on top of the bars. 我已经计算了总数的计数和百分比,但无法弄清楚如何在条形图的顶部添加百分比。 I'm trying to use geom_text, but not able to get it work. 我正在尝试使用geom_text,但无法使其正常工作。

A minimal example: 一个最小的例子:

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)

I have looked at other answers like How to add percentage or count labels above percentage bar plot? 我看过其他答案,例如如何在百分比条形图上方添加百分比或计数标签? , but in those examples, both the y axis and labels show percents. ,但在这些示例中,y轴和标签都显示百分比。 I am trying to show counts on the y axis and percents in the labels. 我试图显示y轴上的计数和标签中的百分数。

Just use percent as label. 只需使用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)

在此输入图像描述

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM