Multiple ggplot2 plots with plotly

10,942

Solution 1

Use the subplot function of plotly:

subplot(p1, p2, nrows = 2, margin = 0.04, heights = c(0.6, 0.4))

Solution 2

I'm having this problem myself and I don't think a solution currently exists to do this in the way you're describing.

The gg2list function contained in the call to ggplotly expects to be able to iterate over a ggplot object's layers to create the corresponding plotly object. If you step into the ggplotly function with RStudio's debugger, you can see the various ways in which it attempts to iterate across the object it receives in order to extract its properties.

It doesn't know what to do with the object returned by the arrangeGrob function because it's not just a single ggplot object (it's a grob arrangement, etc).

Calling class() on the objects in question illustrates this point somewhat.

> class(g1)  
[1] "gg"     "ggplot"

> class(g)  
[1] "arrange" "ggplot"  "gTree"   "grob"    "gDesc" 

I think in order to have multiple plots heads up in the same plotly object, we will need to use the facet options in ggplot or the native plotly R bindings. Unfortunate, because gridExtra is very powerful and flexible, but the ggplot translation mechanism doesn't seem to be able to handle it.

Share:
10,942

Related videos on Youtube

Fisseha Berhane
Author by

Fisseha Berhane

Updated on May 01, 2020

Comments

  • Fisseha Berhane
    Fisseha Berhane about 4 years

    I want to use ggplot2 with grid.arrange to generate multiple plots with plotly. Some thing similar to this:

    library(ggplot2)
    library(gridExtra)
    library(plotly)
    
    
    g1<-ggplot(mpg, aes(displ, hwy, color=factor(year)))+geom_point()
    
    g2<-ggplot(mpg, aes(cyl, hwy, color=factor(year)))+geom_point()
    
    g<-grid.arrange(g1,g2,ncol=2)
    
    ggplotly(g)
    

    However, I am getting "Error in gg2list(p) : No layers in plot"

    Any suggestions

    • Mike Wise
      Mike Wise over 8 years
      I can't even get plotly to install in R 3.1.3. What version are you using?
    • Fisseha Berhane
      Fisseha Berhane over 8 years
  • Ben
    Ben over 5 years
    but subplot seems to provide additional traces for each subplot. For example, I would like to plot three plots which are basically the same but subplot treats them as if they were different.