With some adjustments to the solution of @MrFlick this can be achieved like so:
Instead of only computing yintercept
I adjusted MrFlick's function to replace y
with the mean(y)
which ensures that the labels are put on the y-position of the mean lines.
Instead of returning the whole dataset the adjusted function returns only one row, whereby I set x
to mean(x)
. This ensures that we only get one label.
With these adjustments you can can add labels to the mean lines via
geom_text(aes(x = 10, label = round(..yintercept.., digits = 2)), stat = "mean_line", vjust = -1, hjust = 0)
Try this:
library(ggplot2)
StatMeanLine <- ggproto("StatMeanLine", Stat,
compute_group = function(data, scales) {
transform(data, x = mean(x), y = mean(y), yintercept=mean(y))[1,]
},
required_aes = c("x", "y")
)
stat_mean_line <- function(mapping = NULL, data = NULL, geom = "hline",
position = "identity", na.rm = FALSE, show.legend = NA,
inherit.aes = TRUE, ...) {
layer(
stat = StatMeanLine, data = data, mapping = mapping, geom = geom,
position = position, show.legend = show.legend, inherit.aes = inherit.aes,
params = list(na.rm = na.rm, ...)
)
}
ggplot(mtcars, aes(mpg, cyl)) +
stat_mean_line(color="red") +
geom_text(aes(x = 10, label = round(..yintercept.., digits = 2)), stat = "mean_line", vjust = -1, hjust = 0) +
geom_point() +
facet_wrap(~ gear)
