'How to customize hovertext for ggplotly() object that contains two (or more) geoms?

Issue:

The hovertext as shown below doesn't display the correct "mean_mpg:" when I hover over the point: Hovering over point in plotly bar graph

It should read instead what is displayed correctly when I hover over the bar itself: Hovering over bar in plotly bar graph

I haven't dug deeply into the source code of ggplotly(), but I think when ggplotly is generating the hovertext, it's looking for the aesthetics "x" and "y", and it's finding "x" and "y" specified in both geoms, but for some reason it's incorrectly updating the "mean_mpg:" value with the "mpg" value.

I would like to be able to customize the hovertext separately for each of the geoms in my reprex (e.g. geom_col() and geom_point()) so I can display the correct values.

Would greatly appreciate a solution that still works with ggplotly(), as the real graph I have is much more complex. However plot_ly() solutions are also appreciated as that will likely give me greater insight into the underlying issue(s).

Reprex:

library(ggplot2)
library(dplyr)
library(plotly)

grouped_data <- mtcars %>%
  group_by(gear) %>%
  mutate(mean_mpg = mean(mpg)) %>%
  ungroup()

plot <- ggplot(grouped_data %>% 
         distinct(gear, mean_mpg, .keep_all = TRUE), 
       aes(x = gear,
           y = mean_mpg)) + 
  geom_col() +
  geom_point(data = grouped_data, aes(x = gear, y = mpg))

ggplotly(plot)


Solution 1:[1]

I dont know why but:

geom_point(data = grouped_data, aes(x = gear, y = mpg,label=mean_mpg))

gives the desired result but thorws a warning message.

enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 user12256545