2
votes

I'm wondering if it's possible to convert a plotly object to a ggplot2 object in R? I have a plot object of class plotly htmlwidget.

I've tried the as.ggplot() function from the ggplotify package, but get the following error

Error in UseMethod("as.grob") : no applicable method for 'as.grob' applied to an object of class "c('plotly', 'htmlwidget')"

Is anyone aware of any alternative methods?

Background: I'm trying to arrange multiple Sankey diagrams into a single plot (e.g., using grid.arrange()). There's another question that suggests using Rshiny, but I'm wondering if it'd be possible to convert to a static ggplot object instead.

Here's a reproducible example:

  library(plotly)
  library(ggplotify)
  p <- plot_ly(
    type = "sankey",
    orientation = "h",
    width = 600,
    height = 400,

    node = list(
      label = c(c('A','B'), c('A','B')),
      pad = 15,
      thickness = 20,
      line = list(
        color = "black",
        width = 0.5
      )
    ),

    link = list(
      source = c(0,1,0,1),
      target = c(2,2,3,3),
      value =  c(1,2,3,4)
    )
  )
  class(p)
  as.ggplot(p)
1

1 Answers

2
votes

You don't need to convert to ggplot2 to arrange your plotly objects. Instead, the plotly package has a very nice and customizable subplot() function for you to use. Like:

p <- subplot(p1, p2, p3, p4, nrows = 2)

The function can arrange the plots in any fashion you like, I suggest you check out the gallery online for ideas:

https://plot.ly/r/subplot-charts/

But to answer your question, no, there is no way to convert a plotly object to a ggplot2 one.