【问题标题】:Adding percentage labels to a barplot with y-axis 'count' in R在 R 中使用 y 轴“计数”将百分比标签添加到条形图
【发布时间】:2020-02-07 14:27:01
【问题描述】:

我想为条形图添加每个齿轮的百分比标签,但保留计数 y 比例。 例如。 10% 的“3 档”是“4 缸”

library(ggplot)

ds <- mtcars
ds$gear <- as.factor(ds$gear)

p1 <- ggplot(ds, aes(gear, fill=gear)) +
  geom_bar() +
  facet_grid(cols = vars(cyl), margins=T) 

p1

理想情况下仅在 ggplot 中,不添加 dplyr 或 tidy。我找到了其中一些解决方案,但随后我的原始数据出现了其他问题。

编辑:建议这是重复的: enter link description here

我之前也看到了这个,但无法将该代码集成到我想要的代码中:

# i just copy paste some of the code bits and try to reconstruct what I had earlier
ggplot(ds, aes(gear, fill=gear)) +
  facet_grid(cols = vars(cyl), margins=T) +       
  # ..prop.. meaning %, but i want to keep the y-axis as count
  geom_bar(aes(y = ..prop.., fill = factor(..x..)), stat="count") +  
  # not sure why, but I only get 100% 
  geom_text(aes( label = scales::percent(..prop..),
             y= ..prop.. ), stat= "count", vjust = -.5)

【问题讨论】:

    标签: ggplot2 count label bar-chart percentage


    【解决方案1】:

    问题是 ggplot 不知道每个方面都是一个组。 This very useful tutorial 提供了一个很好的解决方案。只需添加aes(group = 1)

    附:一开始,我常常很不情愿,害怕自己操纵我的数据并预先计算数据框以进行绘图。但是没有必要担心!实际上,首先将数据塑造/聚合成正确的形式,然后绘制/分析新数据通常更容易(也更安全!)。

    library(tidyverse)
    library(scales)
    
    ds <- mtcars
    ds$gear <- as.factor(ds$gear)
    

    第一个解决方案:

    ggplot(ds, aes(gear, fill = gear)) +
      geom_bar() +
      facet_grid(cols = vars(cyl), margins = T) +
      geom_text(aes(label = scales::percent(..prop..), group = 1), stat= "count")
    

    编辑回复评论

    显示各个方面的百分比对于该图的读者来说是相当混乱的,我可能会建议不要使用这种可视化。你不会在这里绕过数据操作。这里的挑战是包括您的“侧面边距”。我创建了两个摘要数据框并将它们绑定在一起。

    
    ds_count <- 
      ds %>% 
      count(cyl, gear) %>% 
      group_by(gear) %>% 
      mutate(perc = n/sum(n)) %>% 
      ungroup %>% 
      mutate(cyl = as.character(cyl))
    
    ds_all <- 
      ds %>% 
      count(cyl, gear) %>% 
      group_by(gear) %>% 
      summarise(n = sum(n)) %>% 
      mutate(cyl = 'all', perc = 1)
    
    ds_new <- bind_rows(ds_count, ds_all)
    
    ggplot(ds_new, aes(gear, fill = gear)) +
        geom_col(aes(gear, n, fill = gear)) +
        facet_grid(cols = vars(cyl)) +
        geom_text(aes(label = scales::percent(perc)), stat= "count")
    

    IMO,更好的方法是简单地交换 x 和构面变量。然后你就可以像上面那样使用ggplots汇总函数了。

    ggplot(ds, aes(as.character(cyl), fill = gear)) +
      geom_bar() +
      facet_grid(cols = vars(gear), margins = T) +
      geom_text(aes(label = scales::percent(..prop..), group = 1), stat= "count")
    

    reprex package (v0.3.0) 于 2020 年 2 月 7 日创建

    【讨论】:

    • 很好,谢谢,但不幸的是还不是我想要的。现在当你总结例如红条的百分比:9+29+86 你得到超过 100%。本质上,我想显示一个圆柱体中每个齿轮的百分比,以便在总结所有相同的齿轮时得到 100%。'
    猜你喜欢
    • 2018-12-15
    • 2016-10-15
    • 2017-11-27
    • 2021-07-17
    • 1970-01-01
    • 2021-09-12
    • 2014-12-07
    相关资源
    最近更新 更多