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

时间:2016-10-25 21:22:55

标签: r ggplot2

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

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

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

1 个答案:

答案 0 :(得分:20)

在ggplot之外预先计算您需要的数量是最容易的,因为很难跟踪ggplot计算的内容以及这些数量的存储和可用位置。

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

library(dplyr)

mtcars %>% count(cyl = factor(cyl), gear = factor(gear)) %>% 
    ungroup() %>%    # drop if you want percentages per cylinder
    mutate(pct = prop.table(n) * 100)

## # A tibble: 8 × 4
##      cyl   gear     n    pct
##   <fctr> <fctr> <int>  <dbl>
## 1      4      3     1  3.125
## 2      4      4     8 25.000
## 3      4      5     2  6.250
## 4      6      3     2  6.250
## 5      6      4     4 12.500
## 6      6      5     1  3.125
## 7      8      3    12 37.500
## 8      8      5     2  6.250

如果你愿意,可以直接输入或直接输入ggplot:

mtcars %>% count(cyl = factor(cyl), gear = factor(gear)) %>% 
    ungroup() %>%
    mutate(pct = prop.table(n) * 100) %>% 
    ggplot(aes(x = cyl, y = pct, fill = gear)) + 
    geom_bar(stat = 'identity', position = 'dodge') + 
    geom_text(aes(y = pct + .5,    # nudge above top of bar
                  label = paste0(pct, '%')),    # prettify
              position = position_dodge(width = .9), 
              size = 3)

barplot with dodged labels

如果你真的想把它全部保留在ggplot内部,你可以geom_text使用stat = 'count'stat_count geom = "text" ggplot(data = mtcars, aes(x = factor(cyl), fill = factor(gear))) + geom_bar(aes(y = prop.table(..count..) * 100), position = "dodge") + geom_text(aes(y = prop.table(..count..) * 100 + 0.5, label = paste0(prop.table(..count..) * 100, '%')), stat = 'count', position = position_dodge(.9), size = 3) + labs(x = 'cyl', y = 'pct', fill = 'gear') ,如果你愿意的话):

NSRange

绘制完全相同的东西。