rggplot2plotlyggplotlygeom-area

R geom_area tooltip always displays the same value


Using the following reprex, when hovering over the upper or lower line, the tooltip keeps showing the same values. Why is that and is there any workaround?

library(ggplot2)
library(plotly)

df <- data.frame(a = c(2020,2021,2022,2020,2021,2022),
                 b = c('Product A','Product A','Product A','Product B','Product B','Product B'),
                 c = c(500,540,630,70,140,100))

plot <- ggplot(df, aes(x = a, y = c, fill = b)) +
  geom_area(position = 'stack')
  # geom_bar(stat = 'identity', position = 'stack')
ggplotly(plot)

If you comment out the geom_area row and include the geom_bar row, you will notice the problem disappears.


Solution

  • This is due to a change in ggplot2 (introduced sometime in the last year or so) which for a geom_area now uses stat="align" and does some interpolation. From the docs (?geom_area)

    To facilitate stacking, the default stat = "align" interpolates groups to a common set of x-coordinates. To turn off this interpolation, stat = "identity" can be used instead.

    Apprarently this change is not supported by plotly (and I'm wondering whether this feature can be supported at all). As a result the text attribute will default to the value of the first data point (figured that out by inspecting the plotly_json() object and when trying to manually add the tooltip text).

    But as the docs suggest you can fix that by switching to stat="identity":

    library(plotly, warn = FALSE)
    
    plot <- ggplot(df, aes(x = a, y = c, fill = b)) +
      geom_area(stat = "identity")
    
    ggplotly(plot)
    

    enter image description here