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

Time:05-17

In ggplot2/stat_summary, how to add the median value as label to plot ? Thanks!

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

CodePudding user response:

One potential option is to use after_stat() to get the labels, i.e.

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))

Created on 2022-05-16 by the reprex package (v2.0.1)

  • Related