首页 > 解决方案 > 使用 R / ggplot2 将标签添加到 geom_bar() 内的单个 %

问题描述

bgraph <- ggplot(data = data, aes(x = location)) +
  geom_bar(aes(fill = success))

success是一个百分比,计算为 4 个类别的因子,具有数据集的不同 4 个结果。我可以很容易地单独计算它们,但是由于ggplot当前构成,它们是由geom_bar(aes(fill=success)).

data <- as.data.frame(c(1,1,1,1,1,1,2,2,3,3,3,3,4,4,4,4,4,4,
                        4,4,5,5,5,5,6,6,6,6,6,6,7,7,7,7,7))
data[["success"]] <- c("a","b","c","c","d","d","a","b","b","b","c","d",
                       "a","b","b","b","c","c","c","d","a","b","c","d",
                       "a","b","c","c","d","d","a","b","b","c","d")
names(data) <- c("location","success")
bgraph <- ggplot(data = data, aes(x = location)) +
  geom_bar(aes(fill = success))
bgraph

如何获得各个百分比的标签?更具体地说,我希望每个条形图有 4 个单独的百分比。一种分别代表黄色、浅橙色、橙色和红色。% 加起来等于 1。

条状图

标签: rggplot2

解决方案


如何使用其中的相对频率创建一个摘要框架,location然后将其与geom_col()and一起使用geom_text()

# Create summary stats
tots <-
  data %>%
  group_by(location,success) %>%
  summarise(
    n = n()
  ) %>%
  mutate(
    rel = round(100*n/sum(n)),
  )

# Plot
ggplot(data = tots, aes(x = location, y = n)) +
  geom_col(aes(fill = fct_rev(success))) + # could only get it with this reversed
  geom_text(aes(label = rel), position = position_stack(vjust = 0.5))

输出: 带有居中标签的条形图


推荐阅读