1

I have used MrFlicks solution to add different horizontal mean lines to plots shown with facet_grid.

It works great, but I was wondering if it would be possible to add some individual text next to the different lines?

My question is: Is it possible to incorporate something like this in the code? And how would you do it?

geom_text(aes(.7,mean(variable),label = round(mean(variable),digits = 2), vjust = -1))
Z.Lin
  • 28,055
  • 6
  • 54
  • 94
Kaare K
  • 11
  • 1

1 Answers1

0

With some adjustments to the solution of @MrFlick this can be achieved like so:

  1. 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.

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

stefan
  • 90,330
  • 6
  • 25
  • 51