rggplot2quarto

Is there a way to add a pop-up window to facet_wrap ggplot titles that shows title descriptions in Quarto?


Say I have this boxplot rendered within a Quarto document:

library(tidyverse)
library(ggplot2)
data(iris)

iris %>%
  pivot_longer(cols = Sepal.Length:Petal.Width, 
               names_to = 'metric', 
               values_to = 'value') %>%
  ggplot(aes(x=metric, y=value)) +
  geom_boxplot(aes(fill = Species)) +
  facet_wrap(~metric, scales = 'free')

enter image description here

Is it possible to add a pop-up window, or a hover text, to each facet title such that when you click or hover over it, it shows a description of the title?

descriptions <- c('Petal length (cm)', 'Petal Width (cm)', 'Sepal Length (cm)', 'Sepal Width (cm)')

Solution

  • One option would be to use ggiraph which allows to make a ggplot2 interactive. For your use case it's sufficient to leverage facet_wrap_interactive and labeller_interactive to add a tooltip to the strip texts:

    ---
    title: "Add tooltip to ggplot2 strip text"
    format: html
    ---
    
    ```{r}
    descriptions <- c("Petal length (cm)", "Petal Width (cm)", "Sepal Length (cm)", "Sepal Width (cm)")
    names(descriptions) <- c("Petal.Length", "Petal.Width", "Sepal.Length", "Sepal.Width")
    ```
    
    ```{r message=FALSE}
    library(tidyverse)
    library(ggiraph)
    
    gg <- iris %>%
      pivot_longer(
        cols = -Species,
        names_to = "metric",
        values_to = "value"
      ) %>%
      mutate(metric = factor(metric)) |>
      ggplot(aes(x = metric, y = value)) +
      geom_boxplot(aes(fill = Species)) +
      facet_wrap_interactive(
        ~metric,
        scales = "free",
        labeller = labeller_interactive(
          aes(tooltip = descriptions[metric])
        )
      )
    
    girafe(ggobj = gg)
    ```
    

    enter image description here