由于它们没有匹配的比例,ggplot 不允许我们将它们一个一个地绘制在另一个之上。 (ggplot 甚至不允许两个 y 尺度)为了解决这个问题,我们必须将它们视为图像而不是绘图。
为了使 to 图像尽可能相似,我们需要去除除线条之外的所有内容。拥有轴、标签、标题等会“错位”“图”。
library(ggplot2)
library(magick)
#> Linking to ImageMagick 6.9.7.4
#> Enabled features: fontconfig, freetype, fftw, lcms, pango, x11
#> Disabled features: cairo, ghostscript, rsvg, webp
df_1 <- data.frame(x=c(1:200), y=rnorm(200))
df_2 <- rpois(100000, 1)
df_2 <- data.frame(table(df_2))
df_2$df_2 <- as.numeric(levels(df_2$df_2))[df_2$df_2]
p1 <- ggplot() +
geom_line(data=df_1, aes(x=x,y=y)) +
theme_void() +
theme(
panel.background = element_rect(fill = "transparent"), # bg of the panel
plot.background = element_rect(fill = "transparent", color = NA), # bg of the plot
panel.grid.major = element_blank(), # get rid of major grid
panel.grid.minor = element_blank(), # get rid of minor grid
legend.background = element_rect(fill = "transparent"), # get rid of legend bg
legend.box.background = element_rect(fill = "transparent") # get rid of legend panel bg
)
ggsave(filename = 'plot1.png', device = 'png', bg = 'transparent')
#> Saving 7 x 5 in image
p2 <- ggplot() +
geom_line(data=df_2, aes(x=df_2,y=Freq)) +
theme_void() +
theme(
panel.background = element_rect(fill = "transparent"), # bg of the panel
plot.background = element_rect(fill = "transparent", color = NA), # bg of the plot
panel.grid.major = element_blank(), # get rid of major grid
panel.grid.minor = element_blank(), # get rid of minor grid
legend.background = element_rect(fill = "transparent"), # get rid of legend bg
legend.box.background = element_rect(fill = "transparent") # get rid of legend panel bg
)
ggsave(filename = 'plot2.png', device = 'png', bg = 'transparent')
#> Saving 7 x 5 in image
cowplot::plot_grid(p1, p2, nrow = 1)
两个情节:
plot1 <- image_read('plot1.png')
plot2 <- image_read('plot2.png')
img <- c(plot1, plot2)
image_mosaic(img)
由reprex package (v0.3.0) 于 2020-01-10 创建
两个“情节”结合起来: