rggplot2plotlyggplotly

geom_xspline not implemented in plotly - getting error message when using ggplotly() function (R)


I get an error message when trying to implement geom_xspline with plotly in R.

I get the desired graph in ggplot2 but the plot cannot be converted to a plotly object when using the ggplotly function. You can find the code showcasing this below.

library(pacman)
pacman::p_load(tidyverse, datasets, plotly, ggplotly, ggalt)

# airmiles built-in dataset: 
airmiles <- datasets::airmiles
year <- 1937:1960
airmiles <- data.frame(year = year, airmiles = airmiles)


# "line" plot using geom_xspline from ggalt package: 
plot_airmiles <- ggplot(data = airmiles, 
              aes(x = year, y = airmiles)) + 
  geom_point(alpha = 0.75) + 
  geom_xspline(spline_shape = -0.7) +
  scale_y_continuous(n.breaks = 10) 

plot_airmiles

static plot using ggplot2

# interactive plot: using ggplotly doesn't work
ggplotly(plot_airmiles)

error message ggplotly

Could this be implemented in plotly? Is there any way I can still produce the interactive graph in plotly without waiting for this to be implemented?

The plotly documentation (https://linking.plotly-r.com/custom-geoms) mentions the possibility of creating custom geoms and using the to_basic() function from the plotly package to “convert” the custom geom into a geom plotly understands.
In the link above, the authors provide an example for geom_xspline specifically but their method and code don’t work unfortunately.

I tried converting a ggplot2 plot with a xspline geom into a plotly object (interactive plot). I was expecting this to work like it does for other geom but it turns out plotly doesn't support the xspline geom.


Solution

  • A possible workaround would be to use a geom_line with stat=ggalt:: StatXspline:

    pacman::p_load(tidyverse, datasets, plotly, ggalt)
    
    year <- 1937:1960
    airmiles_df <- data.frame(year = year, airmiles = airmiles)
    
    gg <- ggplot(
      data = airmiles_df,
      aes(x = year, y = airmiles)
    ) +
      geom_point(alpha = 0.75) +
      geom_line(
        stat = ggalt::StatXspline,
        spline_shape = -0.7
      ) +
      scale_y_continuous(n.breaks = 10)
    
    ggplotly()
    

    enter image description here