【问题标题】:Adding labels to individual % inside geom_bar() using R / ggplot2 [duplicate]使用 R / ggplot2 将标签添加到 geom_bar() 内的单个 % [重复]
【发布时间】:2019-12-06 01:39:18
【问题描述】:
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。

【问题讨论】:

  • 请提供您的数据样本以使该问题可重现
  • 我可能不明白你在追求什么,但position = 'fill' 会成功吗? geom_bar(aes(fill = success), position = 'fill')
  • @AHart,不,这证明图表占图表区域的 100%。我的目标是让百分比标签悬停在每个条形的相应颜色上。

标签: r ggplot2


【解决方案1】:

也许有一种方法可以直接在ggplot 中执行此操作,但在dplyr 中进行一些预处理,您将能够获得所需的输出。

library(dplyr)
library(ggplot2)

data %>%
  count(location, success) %>%
  group_by(location) %>%
  mutate(n = n/sum(n) * 100) %>%
  ggplot() + aes(x = location, n, fill = success,label = paste0(round(n, 2), "%")) +
  geom_bar(stat = "identity") +
  geom_text(position=position_stack(vjust=0.5))

【讨论】:

  • 谢谢你,Ronak,这是完美的
【解决方案2】:

使用location 内的相对频率创建一个摘要框架,然后将其与geom_col()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))

输出:

【讨论】:

    猜你喜欢
    • 2020-09-07
    • 1970-01-01
    • 2016-01-13
    • 2021-11-18
    • 1970-01-01
    • 2021-07-24
    • 2011-09-21
    • 2020-06-25
    • 2023-03-31
    相关资源
    最近更新 更多