【问题标题】:How to add y value average text to geom_bar?如何将y值平均文本添加到geom_bar?
【发布时间】:2022-12-19 00:57:48
【问题描述】:

ggplot(aes(x=MALE, y=AMOUNT, fill=MALE)) + geom_bar(stat="summary", fun="mean") +
  ylab("Avg Amount") + theme(axis.title.x = element_blank())

鉴于我在创建图表时已经创建了 stat='summary' & fun='mean' ,如何将 y 值添加到条形图的顶部?

【问题讨论】:

    标签: r ggplot2 mean geom-text


    【解决方案1】:

    要在栏顶部添加 y 值作为标签,您可以执行以下操作:

    geom_text(aes(label = after_stat(y)), stat = "summary", fun = "mean", vjust = -.1)
    

    使用 mtcars 作为示例数据和一些额外的标签格式:

    library(ggplot2)
    
    ggplot(mtcars, aes(x = factor(cyl), y = mpg, fill = factor(cyl))) +
      geom_bar(stat = "summary", fun = "mean") +
      geom_text(aes(label = after_stat(sprintf("%.1f", y))), stat = "summary", fun = "mean", vjust = -.1) +
      ylab("Avg Amount") +
      theme(axis.title.x = element_blank())
    

    【讨论】:

      猜你喜欢
      • 2015-01-13
      • 2016-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-16
      • 2021-01-31
      • 2011-09-27
      • 1970-01-01
      相关资源
      最近更新 更多