Search code examples
rggplot2facet-wrap

R drawing baseline in facet_wrap specific to each facet


Let's say I have the following dataset:

set.seed(42)

data <- data.frame(type = sample(LETTERS[1:2], 40, replace = T),
                   condition = sample(c("Control", "Treatment"), 40, replace = T),
                   measurement = runif(40))

And I'd like to create the facetted graph:

ggplot(data, aes( x= condition, y = measurement))+
  geom_point()+
  facet_wrap(~type)

I'd like also to show the baseline (with geom_hline, for example), that equals mean of control values (mean(data$measurement[data$condition == "Control"]). But because control values will be different in different types (meaning facets on the graph), I can't just calculate one single mean. As they will be different between the facets.

Is there any way to specify yintercept for geom_hline between different facets ?

Something like this, but with the specified yintercept value, calculating the mean values for the control group for each individual facet:

ggplot(data, aes( x= condition, y = measurement))+
 geom_point()+
 geom_hline(yintercept= mean(data$measurement[data$condition == "Control"]),
            linetype="dashed", 
            color = "red", size=1)+
 facet_wrap(~type)

Thanks a lot! Best regards, Eugene


Solution

  • You can use stat_summary with fun = mean and geom = "hline", passing only the control subset to the data parameter. You can map yintercept to the y value calculated by the stat.

    ggplot(data, aes(x = condition, y = measurement))+
      geom_point() +
      stat_summary(fun = mean, geom = "hline", aes(yintercept = after_stat(y)),
                   data = data[data$condition == "Control",], color = "red",
                   linetype = "dashed") +
      facet_wrap(~type)
    

    enter image description here