rggplot2tooltipggiraph

Is it possible to use ggiraph interactive functions with ggplots generated using stat_summary


I am using stat_summary to generate a column plot from a dataframe. I would like to report the values to the user via tooltips using geom_col_interactive from ggiraph.

I can get the values from the ggplot using ggplot_build and construct a tooltip as below. However, I cannot work out how to use ggiraph with the plot generated using stat_summary to present tooltips interactively. I could of course use the summary_values tibble and generate a different ggplot using geom_col_interactive, but this would defeat the purpose of using stat_summary (which lends itself nicely to faceting). Is there any way to do this? Or must I use summarySE from Rmisc to generate the tibble to be plotted using geom_col_interactive?

library(tidyverse)

mpg_histogram <- ggplot(mpg, aes(x=as.factor(cyl), fill = as.factor(cyl))) +
  stat_summary(aes(y = hwy), fun = "mean", geom = "bar") +
  stat_summary(aes(y = hwy), fun.data = mean_se,  
               geom = "errorbar", width = 0.2, size = 0.2)

enter image description here

summary_values <- ggplot_build(mpg_histogram)$data[[2]]
summary_values <- summary_values %>%
  mutate(mean = round(y,1), sem = round(ymax-y,1)) %>%
  mutate(tooltip = paste("Mean mpg:",mean,"+/-",sem)) %>%
  select(c(mean,sem,tooltip))

Solution

  • One approach to achieve your desired result via stat_summary would be to pass the ggiraph:::GeomInteractiveCol to the geom argument. However, be aware that GeomInteractiveCol is not exported by ggiraph and so requires to use :::. Additionally, to have both the mean and the standard error in the tooltip requires to switch to fun.data="mean_se". For convenience I make use of a simple custom function to create the tooltip:

    library(ggplot2)
    library(ggiraph)
    
    tooltip <- function(y, ymax, accuracy = .01) {
      mean <- scales::number(y, accuracy = accuracy)
      sem <- scales::number(ymax - y, accuracy = accuracy)
      paste("Mean mpg:", mean, "+/-", sem)
    }
    
    gg_point <- ggplot(mpg, aes(x = as.factor(cyl), fill = as.factor(cyl))) +
      stat_summary(aes(y = hwy, tooltip = after_stat(tooltip(y, ymax))),
        fun.data = "mean_se", geom = ggiraph:::GeomInteractiveCol
      ) +
      stat_summary(aes(y = hwy),
        fun.data = mean_se,
        geom = "errorbar", width = 0.2, size = 0.2
      )
    
    girafe(ggobj = gg_point)
    

    enter image description here