在 ggplot2/stat_summary 中,如何将“中值”值作为标签添加到绘图中(如 geom_text())

In ggplot2/stat_summary, how to add the `median` value as label to plot (as geom_text())

在ggplot2/stat_summary中,如何将median值作为标签添加到绘图中?谢谢!

library(ggplot2)
d <- ggplot(mtcars, aes(cyl, mpg)) + geom_point()
d + stat_summary(fun = "median", colour = "red", size = 2, geom = "point")

一个可能的选择是使用 after_stat() 来获取标签,即

library(ggplot2)
d <- ggplot(mtcars, aes(cyl, mpg)) +
  geom_point()
d + stat_summary(fun = "median", colour = "red", size = 4,
                 geom = "text", aes(label = after_stat(y)),
                 position = position_nudge(x = 0.25))

reprex package (v2.0.1)

于 2022-05-16 创建