0

In the plot below of the data in foo, how can put the text "50%" on the right margin at the median value of each facet? I imagine it's a a geom_text with coord_cartesian(clip = "off") but I don't know how to incorporate the facets.

foo <- data.frame(x=rep(1:50,times=2),y=c(rnorm(50,mean=2),rnorm(50,mean=4)),
                                          z=rep(c("A","B"),each=50))
bar <- foo %>% group_by(z) %>% summarise(med=median(y))

ggplot(foo,aes(x,y,color=z)) + geom_point() + 
  geom_hline(data=bar,aes(yintercept = med,col=z)) +
  facet_wrap(z~.,ncol = 1) +
  theme(legend.position = "none",
        plot.margin = unit(c(1,3,1,1), "lines"))
# place "50%" in right margin at bar$med for each facet
user111024
  • 723
  • 3
  • 15

1 Answers1

1

Instead of adding an annotation to the plot margins you could use the secondary axis trick which means to add your annotation via a secondary axis. As you want to place the annotation at different positions I use ggh4x::facetted_pos_scales from the ggh4x package which allows to individually set the breaks for each facet. Doing so requires to set scales = "free_y" in facet_wrap and as this will change the limits, I use the limits argument to get the same limits for each facet:

library(ggplot2)
library(ggh4x)

set.seed(123)

scale_dup <- function(x) {
  scale_y_continuous(
    sec.axis = dup_axis(
      breaks = bar[bar$z == x, "med", drop = TRUE],
      labels = "50%"
    ), limits = range(foo$y)
  )
}

ggplot(foo, aes(x, y, color = z)) +
  geom_point() +
  geom_hline(data = bar, aes(yintercept = med, col = z)) +
  facet_wrap(z ~ ., ncol = 1, scales = "free_y") +
  theme(
    legend.position = "none"
  ) +
  facetted_pos_scales(
    y = list(
      z == "A" ~ scale_dup("A"),
      z == "B" ~ scale_dup("B")
    )
  )

enter image description here

stefan
  • 90,330
  • 6
  • 25
  • 51