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

and*_*ang 2 ggplot2

在 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")
Run Code Online (Sandbox Code Playgroud)

jar*_*rot 6

一种潜在的选择是使用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))
Run Code Online (Sandbox Code Playgroud)


要舍入值,您可以使用round()

d + stat_summary(fun = "median", colour = "red", size = 4,
                 geom = "text", aes(label = round(after_stat(y), 0)),
                 position = position_nudge(x = 0.25))
Run Code Online (Sandbox Code Playgroud)

创建于 2023 年 10 月 24 日,使用reprex v2.0.2