Search code examples
rggplot2textlabelggtext

How do I correctly select the label to place on top of the highest point of the Y-axis of a facet-separated plot?


I have a plot which I have separated by facets for each group. At the highest point of the Y axis I want to put the corresponding Y value, for this I am using the ggtext package and the geom_richtext() function. Although I use group = Group within the geom_richtext() function, the label does not appear as I expect.

In the MWE I would like the facets of groups A, B and C to have the values of 100, 500 and 1000, respectively, appear on top of each peak. Could someone help me with a suggestion?

library(ggplot2)
library(ggtext)

Group <- c("A", "B", "C")
Time <- 0:10

DF <- expand.grid(Time = Time,
                  Group = Group)

DF$Y <- c(rep(1,5), 100, rep(1,5),
          rep(1,5), 500, rep(1,5),
          rep(1,5), 1000, rep(1,5))

ggplot(data = DF,
       aes(x = Time,
           y = Y)) +
  geom_line() +
  facet_grid(Group ~ .) +
  geom_richtext(aes(label = max(Y),
                    group = Group)) +
  theme_bw()

enter image description here


Solution

  • One option would be to pass a filtered dataset to geom_richtext which only includes the max values per Group:

    library(ggplot2)
    library(ggtext)
    library(dplyr)
    
    ggplot(data = DF,
           aes(x = Time,
               y = Y)) +
      geom_line() +
      facet_grid(Group ~ .) +
      geom_richtext(data = DF %>% group_by(Group) %>% slice_max(Y, n = 1), aes(label = Y,
                        group = Group)) +
      theme_bw()