23

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

2
  • I can't even get plotly to install in R 3.1.3. What version are you using? Commented Oct 5, 2015 at 21:58
  • See this: plot.ly/r/getting-started Commented Oct 7, 2015 at 23:27

2 Answers 2

29

Use the subplot function of plotly:

subplot(p1, p2, nrows = 2, margin = 0.04, heights = c(0.6, 0.4))
Sign up to request clarification or add additional context in comments.

2 Comments

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.
@Ben, is it possible to add a title to this?
5

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.