在ggplot2中的geom_bar顶部显示总数的百分比,同时在y轴上显示计数 [英] Show percent of total on top of geom_bar in ggplot2 while showing counts on y axis

查看:745
本文介绍了在ggplot2中的geom_bar顶部显示总数的百分比,同时在y轴上显示计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用ggplot2创建条形图,在y轴上显示计数,但还要在每个条形的顶部显示总数的百分比。我已经计算出总数的百分比和百分比,但无法弄清楚如何将总数的百分比添加到条形图的顶部。我正在尝试使用geom_text,但是无法正常工作。



一个最小的示例:

  iris%>%
group_by(Species)%>%
summary(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'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. 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.

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. I am trying to show counts on the y axis and percents in the labels.

解决方案

Just use percent as label.

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)

这篇关于在ggplot2中的geom_bar顶部显示总数的百分比,同时在y轴上显示计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆