10

Is it possible to combine a ggplotly and a ggplot with patchwork?

Example

This displays the two plots side by side

library(ggplot2)
library(plotly)
library(patchwork)

a <- ggplot(data.frame(1), aes(X1)) + geom_bar()
b <- ggplot(data.frame(1), aes(X1)) + geom_bar()
a + b

But if we convert one to ggplotly, it errors

b  <- ggplotly(b)
a + b
Error: Can't add `b` to a ggplot object.
Run `rlang::last_error()` to see where the error occurred.

Is there a way to work around this?

dss
  • 395
  • 3
  • 11

2 Answers2

15

Plotly has the subplot function to combine multiple plots together:

library(ggplot2)
library(plotly)

df1 <-data.frame(x=1:10, y=1:10)
df2 <- data.frame(x=10:1, y=1:10)

p1<-ggplot(df1, aes(x, y)) +geom_point()
fig1<-ggplotly(p1)

p2<-ggplot(df2, aes(x, y)) +geom_line()
fig2<-ggplotly(p2)

subplot(fig1, fig2, nrows=2)

See https://plotly.com/r/subplots/ for more information and examples.

Dave2e
  • 22,192
  • 18
  • 42
  • 50
  • I think one of the `fig` needs to be kept as ggplot to match the question, but the solution is perfect none the less – dss May 03 '20 at 13:36
  • If one actually specifically wants to use patchwork for this (as the syntax implementation is really nice) is it possible? – Pascoe Jul 16 '20 at 09:44
  • @Pascoe I an interested in the same question you have. It's not we want, but at least we know for sure: https://stackoverflow.com/a/63038534/13402588 – dss Aug 02 '20 at 11:18
  • @dss Ok well then as you say at least we know. Frankly the syntax implementation imho in patchwork is so neat I'm happy enough anyway. Anything else is a bonus.... – Pascoe Aug 18 '20 at 14:22
  • 2
    Any idea how to put 2 plots side by side (as opposed to stacked)? (I intuitively used `ncols` but that isn't a valid parameter to `subplot()`). EDIT: so that's really easy, just omit the `nrows` parameter altogether and it will automatically go side by side. – stevec Jul 25 '21 at 09:49
5

While potentially possible, the maintainer has said it's outside of the current plan

https://github.com/thomasp85/patchwork/issues/70

David Rea
  • 66
  • 1
  • 3