Поскольку у них нет соответствующих масштабов, ggplot не позволит нам нанести их один на другой. (ggplot даже не учитывает две y-шкалы) Чтобы обойти это, мы должны рассматривать их как изображения, а не как графики.
Чтобы изображения были максимально похожи друг на друга, нам нужно вырезать все, кроме линий. Наличие топоров, меток, заголовков и т. Д. c «сместит» «графики».
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)
Создано в 2020-01-10 пользователем представительный пакет (v0.3.0)
Оба «участка» вместе взятые: