【问题标题】:Add count values on top of gghistogram在 gghistogram 顶部添加计数值
【发布时间】:2022-11-23 00:24:02
【问题描述】:

我为我的数据中的不同年龄组做了一个直方图:

> dput(Agedata[1:20,])

structure(list(samples = c("Pt1", "Pt10", "Pt101", "Pt103", "Pt106", 
"Pt11", "Pt17", "Pt18", "Pt2", "Pt24", "Pt26", "Pt27", "Pt28", 
"Pt29", "Pt3", "Pt30", "Pt31", "Pt34", "Pt36", "Pt37"), resp = c("NoResponse", 
"NoResponse", "Response", "NoResponse", "NoResponse", "NoResponse", 
"NoResponse", "Response", "NoResponse", "NoResponse", "NoResponse", 
"NoResponse", "NoResponse", "NoResponse", "Response", "Response", 
"NoResponse", "Response", "NoResponse", "NoResponse"), age = c(58, 
53, 61, 57, 57, 62, 51, 59, 58, 60, 61, 49, 52, 57, 61, 61, 60, 
56, 55, 61), age_group = structure(c(6L, 6L, 7L, 6L, 6L, 7L, 
6L, 6L, 6L, 7L, 7L, 5L, 6L, 6L, 7L, 7L, 7L, 6L, 6L, 7L), levels = c("0-9", 
"10-19", "20-29", "30-39", "40-49", "50-59", "60-69", "70-79", 
"80-89", "90-99"), class = "factor")), row.names = c(NA, 20L), class = "data.frame")

像这样:

library(ggpubr)

gghistogram(Agedata, x = "age_group", bins = 8,
            rug = TRUE,
            color = "resp", fill = "resp", stat = 'count',
            palette = c("red", "green"), main = 'Age ~ Outcome') + ylim(c(0,500)) + theme_bw()

现在如何在每个 bin 的顶部添加计数值?包括红色垃圾箱和绿色垃圾箱?

【问题讨论】:

    标签: r ggplot2 histogram ggpubr


    【解决方案1】:

    我想我会在这里使用普通的旧 geom_bar 而不是 gghistogram。一般来说,像gghistogram 这样的函数可以更轻松地用最少的代码在 ggplot 中产生不错的结果,但是它们缺乏易用性,也失去了灵活性。

    由于您的 bin 是预定义的而不是从连续变量构建的,因此您的数据更适合条形图而不是直方图。它还允许您通过 geom_text 添加文本,而不必首先计算出 gghistogram 在内部使用其美学映射做什么。

    ggplot(Agedata, aes(age_group, color = resp)) +
      geom_bar(aes(fill = after_scale(alpha(colour, 0.4)))) +
      geom_text(stat = 'count', position = position_stack(vjust = 1),
                vjust = -0.2,
                aes(label = after_stat(count), group = resp), color = 'black') +
      scale_color_manual(values = c('red2', 'green3')) +
      theme_bw()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-07
      • 1970-01-01
      • 2017-07-29
      • 1970-01-01
      • 2021-05-22
      • 1970-01-01
      • 1970-01-01
      • 2019-04-01
      相关资源
      最近更新 更多