我想将用 Plotly 和 ggplot2 准备的两张图表合并成一个 PDF。下面,您可以看到用于准备图表的代码:
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()
现在,我想使用 patchwork 库将它们组合成一个方面图。下面,您可以看到命令:
# Combine both
(Treemap_plotly/barchart_ggplot2)
不幸的是,这不起作用。有人可以帮我准备一张包含下图所示的两个图表的面图并以 PDF 格式导出吗?
patchwork
不适用于 plotly
对象。可以在 ggplot2
中创建树形图,但它涉及更多工作或使用 treemapify
等包。
我们可以将树形图保存为图像,然后使用
gridExtra
将图并排放置:
library(dplyr)
library(plotly)
library(ggplot2)
library(magick)
library(grid)
library(gridExtra)
Treemap_plotly_file <- tempfile(fileext = ".png")
#export is soft deprecated, but for now it's the best option
suppressWarnings(invisible(export(Treemap_plotly, file = Treemap_plotly_file)))
my_img <- image_read(Treemap_plotly_file)
barchart_ggplot2<- barchart_ggplot2 + theme(plot.margin = margin(1,0.5,1,0, "cm"))
grid.arrange(rasterGrob(my_img), barchart_ggplot2, widths = c(0.6, 0.4))
但是这看起来会很糟糕,具体取决于图的大小等等。因此,我建议使用
plotly
创建两个图,然后使用 subplot
。
library(dplyr)
library(plotly)
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 = list(text = "Treemap", x = 0.1))
barchart_plotly <- df1 %>%
mutate(clr = "#619CFF") %>%
plot_ly(data = , x = ~dose, y = ~len,
color = ~clr, colors = "#619CFF",
type = "bar", showlegend = F,
text = ~sprintf("<b>%s</b>", len),
textfont = list(color = "black"),
textposition='outside')
subplot(Treemap_plotly, barchart_plotly, widths = c(0.6, 0.3))
创建于 2024-03-26,使用 reprex v2.0.2