I want to combine two charts prepared with Plotly and ggplot2 into one PDF. Below, you can see the code for the preparation of the charts:
library(ggplot2)
library(plotly)
library(dplyr)
library(patchwork)
## 1.Plotly
dt=data.frame(
types= rep("stories",10),
kind= c('kind_1','kind_2','kind_3','kind_1','kind_2','kind_3','kind_1','kind_2','kind_3','kind_1'),
values=seq(1:10))
Treemap_plotly<-plot_ly(data = dt,
type= "treemap",
values= ~values,
labels= ~kind,
parents= ~types,
domain= list(column=0),
name = " ",
textinfo="label+value+percent parent")%>%
layout(title="Treemap")
## 2.ggplot2
df1 <- data.frame(dose=c("D0.5", "D1", "D2"),
len=c(4.2, 10, 29.5))
barchart_ggplot2<-ggplot(data=df1, aes(x=dose, y=len)) +
geom_bar(stat="identity", fill="steelblue")+
geom_text(aes(label=len), vjust=-0.3, size=3.5)+
theme_minimal()
Now, I want to combine them into one facet plot using the patchwork library. Below, you can see the command:
# Combine both
(Treemap_plotly/barchart_ggplot2)
Unfortunately, this does not work. Below is my desired graph:


patchworkdoes not work withplotlyobjects. It's possible to create the treemap inggplot2but it involves some more work or using packages liketreemapify.We could save the treemap graph as an image and then use
gridExtrato put the plots side by side:But this will look janky depending on the size of the plots and whatnot. So, I'd suggest creating both plots with
plotlyand then usesubplot.Created on 2024-03-26 with reprex v2.0.2