【问题标题】:Display Percentage on ggplot Bar Chart in R [duplicate]在R中的ggplot条形图上显示百分比[重复]
【发布时间】:2018-09-17 17:33:46
【问题描述】:

我需要在 R 中的条形图条上显示百分比值。

此代码绘制分类数据,x 为类别,y 为 %。如何修改它以使其在条形本身上显示百分比,而不仅仅是在 y 轴上?

ggplot(data = iris) + 
  geom_bar(mapping = aes(x = Species, y = (..count..)/sum(..count..), fill = Species)) +
  scale_y_continuous(labels = percent)

【问题讨论】:

  • 查看scales 包以获取轴标签,并查看geom_text 以向条形添加文本。
  • 我尝试添加 'geom_text(aes(label = paste0(100*((..count..)/sum(..count..)))),size = 5)'对于文本,但我收到一个错误:总和(计数)错误:参数的无效“类型”(闭包)
  • 啊,我明白你在说什么。你想在栏本身上显示文字,对吧?
  • @divibisan 是的,正是....编辑了问题以澄清这一点
  • 查看this question 除了之前作为骗子发布的那个

标签: r ggplot2 bar-chart percentage


【解决方案1】:

ggplot 中的 ..count.. 助手可以很好地处理简单的情况,但通常最好先在适当的级别聚合数据,而不是在 ggplot 调用中:

library(tidyverse)
library(scales)

irisNew <- iris %>% group_by(Species) %>% 
 summarize(count = n()) %>%  # count records by species
 mutate(pct = count/sum(count))  # find percent of total

ggplot(irisNew, aes(Species, pct, fill = Species)) + 
  geom_bar(stat='identity') + 
  geom_text(aes(label=scales::percent(pct)), position = position_stack(vjust = .5))+
  scale_y_continuous(labels = scales::percent)

vjust = .5 将每个条中的标签居中

【讨论】:

    【解决方案2】:
    ggplot(data = iris, aes(x = factor(Species), fill = factor(Species))) +
    geom_bar(aes(y = (..count..)/sum(..count..)),
             position = "dodge") + 
    geom_text(aes(y = (..count..)/sum(..count..), 
                  label = paste0(prop.table(..count..) * 100, '%')), 
              stat = 'count', 
              position = position_dodge(.9), 
              size = 3)+ 
    labs(x = 'Species', y = 'Percent', fill = 'Species')
    

    【讨论】:

    • 我收到此错误:层错误(数据 = 数据,映射 = 映射,stat = stat,geom = GeomText,: object '..count..' not found
    • .. 表示法在几个版本中被弃用,取而代之的是 stat()
    猜你喜欢
    • 2023-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多