将百分比标签添加到ggplot2中的条形图

uma*_*ani 7 r ggplot2

如何使用geom_text在每个栏顶部添加百分比标签ggplot2?我知道有几个类似的问题已经得到解答.但他们要么只使用1个分类变量,要么在绘图之前计算百分比.
我有以下情节:

ggplot(data = mtcars)+
  geom_bar(aes(x = factor(cyl), 
               y = (..count..)/sum(..count..)*100,
               fill = factor(gear)),
           position = "dodge")  
Run Code Online (Sandbox Code Playgroud)

现在我想在顶部添加百分比标签.如果我使用y = (..count..)/sum(..count..)*100geom_text,它说Error in eval(expr, envir, enclos) : object 'count' not found.

ali*_*ire 22

最简单的方法是在ggplot之外事先计算出你需要的数量,因为很难跟踪ggplot计算的内容以及这些数量的存储和可用位置.

首先,总结一下你的数据:

library(dplyr)
library(ggplot2)

mtcars %>% 
    count(cyl = factor(cyl), gear = factor(gear)) %>% 
    mutate(pct = prop.table(n))
#> # A tibble: 8 x 4
#>   cyl   gear      n    pct
#>   <fct> <fct> <int>  <dbl>
#> 1 4     3         1 0.0312
#> 2 4     4         8 0.25  
#> 3 4     5         2 0.0625
#> 4 6     3         2 0.0625
#> 5 6     4         4 0.125 
#> 6 6     5         1 0.0312
#> 7 8     3        12 0.375 
#> 8 8     5         2 0.0625
Run Code Online (Sandbox Code Playgroud)

保存,如果你喜欢,或直接管道到ggplot:

mtcars %>% 
    count(cyl = factor(cyl), gear = factor(gear)) %>% 
    mutate(pct = prop.table(n)) %>% 
    ggplot(aes(x = cyl, y = pct, fill = gear, label = scales::percent(pct))) + 
    geom_col(position = 'dodge') + 
    geom_text(position = position_dodge(width = .9),    # move to center of bars
              vjust = -0.5,    # nudge above top of bar
              size = 3) + 
    scale_y_continuous(labels = scales::percent)
Run Code Online (Sandbox Code Playgroud)

带有躲闪标签的条形图

如果你真的想保持它的所有内部ggplot,你可以用geom_textstat = 'count'(或stat_countgeom = "text",如果你喜欢):

ggplot(data = mtcars, aes(x = factor(cyl), 
                          y = prop.table(stat(count)), 
                          fill = factor(gear), 
                          label = scales::percent(prop.table(stat(count))))) +
    geom_bar(position = "dodge") + 
    geom_text(stat = 'count',
              position = position_dodge(.9), 
              vjust = -0.5, 
              size = 3) + 
    scale_y_continuous(labels = scales::percent) + 
    labs(x = 'cyl', y = 'pct', fill = 'gear')
Run Code Online (Sandbox Code Playgroud)

绘制完全相同的东西.