Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine ggplotly and ggplot with patchwork?

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?

like image 311
dss Avatar asked May 03 '20 12:05

dss


2 Answers

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.

like image 79
Dave2e Avatar answered Oct 22 '22 06:10

Dave2e


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

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

like image 4
David Rea Avatar answered Oct 22 '22 07:10

David Rea