plotly / plotly.R

An interactive graphing library for R
https://plotly-r.com
Other
2.53k stars 623 forks source link

Support for ggplot stacked geom_area plots? #2320

Open mot12341234 opened 8 months ago

mot12341234 commented 8 months ago

I have a stacked geom_area plot in ggplot which looks fine, but somehow the ggplotly version shows empty. Below is the toy example. (the issue seems to do with position_fill(), if getting rid of it, the plot can run normally)..

R version: 4.3.2, plotly version: 4.10.3

library(tidyverse)
library(plotly)

df <- expand_grid(tibble(x = seq(10), y = seq(10)), g = letters[1:5])
pl <- df %>%
  ggplot() +
  geom_area(aes(x = x, y = y, fill = g), position = 'fill')

ggplotly(pl)
trekonom commented 3 months ago

This issue is most likely due to a change introduced in ggplot2 3.4.0 which now defaults to stat="align" (which does some form of interpolation) for geom_area and which is not fully supported by ggplotly (a related issue arises when it comes to the tooltips, see this SO question).

But for your case that can be fixed by setting stat="identity" in geom_area:

library(plotly, warn=FALSE)
#> Loading required package: ggplot2

df <- tidyr::expand_grid(
  tibble::tibble(x = seq(10), y = seq(10)),
  g = letters[1:5]
)
pl <- ggplot(df) +
  geom_area(aes(x = x, y = y, fill = g),
    position = "fill", stat = "identity"
  )

ggplotly(pl)

Created on 2024-04-27 with reprex v2.1.0