Search code examples
rggplot2plotlyhistogramggplotly

Is there a way to add the bin range label into the tooltip for a histogram using ggplotly in R?


library(tidyverse)
library(ggplot2)
library(plotly)

data(mpg)

ggplotly(
mpg %>% 
  ggplot(aes(x=hwy)) +
  geom_histogram(), 
tooltip = ("all"))

When you hover over the bar, I'd like for the tooltip to show the start and stop of the bin (e.g. 20-21)


Solution

  • Thanks for the simple plot_ly answer. For other reasons, I'd like to preserve ggplot. Here's one possible solution I came up with that extracts the histogram elements from ggbuild_plot() and plots them as a bar graph.

    ggplotly(
    ggplot_build(
      mpg %>% 
        ggplot(aes(x=hwy)) +
        geom_histogram()
    )$data[[1]] %>% 
      ggplot(aes(x=factor(x), y = count, text = paste0("range: ",round(xmin, 1), " - ", round(xmax,1)))) + 
      geom_bar(stat="identity") + 
      theme(axis.text.x = element_blank()),
    tooltip = c("text"))
    

    enter image description here