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)
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))
One approach to achieve your desired result via
stat_summary
would be to pass theggiraph:::GeomInteractiveCol
to thegeom
argument. However, be aware thatGeomInteractiveCol
is not exported byggiraph
and so requires to use:::
. Additionally, to have both the mean and the standard error in the tooltip requires to switch tofun.data="mean_se"
. For convenience I make use of a simple custom function to create the tooltip: