我需要绘制一些简单的线图以及图像。但是,图像的左侧和右侧需要与线条图的左侧和右侧对齐。
这样,我需要一种方法来沿x轴移动和缩放图像以完成此操作。
我当前使用的代码是:
library(tidyverse)
library(grid)
library(gridExtra)
library(cowplot)
library(magick)
df <- tibble(Long_Name_For_X= -10:10,Long_Name_For_Y = x^2,Long_Name_For_Z= x)
testImage <- image_read(file.path("C:/index.jpg"))
p1 <- df %>%
gather(variable,value,-Long_Name_For_X) %>%
ggplot(aes(x=Long_Name_For_X,y=value,color=variable)) +
geom_line()
p2 <- ggdraw() + draw_image(testImage)
plot_grid(p1,p2,ncol=1,align = "v", axis = "l")
答案 0 :(得分:1)
我们需要将图例与图分开,以使其易于对齐。该过程类似于此answer
library(tidyverse)
library(magick)
library(cowplot)
library(patchwork)
x <- -10:10
df <- tibble(Long_Name_For_X = -10:10, Long_Name_For_Y = x^2, Long_Name_For_Z = x)
testImage <- image_read(file.path("./img/index.png"))
p1 <- df %>%
gather(variable, value, -Long_Name_For_X) %>%
ggplot(aes(x = Long_Name_For_X, y = value, color = variable)) +
geom_line()
p2 <- ggdraw() + draw_image(testImage)
# get legend
leg <- get_legend(p1)
# create a blank plot for legend alignment
blank_p <- plot_spacer() + theme_void()
# align legend with the blank plot
p3 <- plot_grid(leg,
blank_p,
nrow = 2)
# align p1 & p2 without any legend
p12 <- plot_grid(p1 + theme(legend.position = 'none'),
p2,
nrow = 2)
# put everything together
final_plot <- plot_grid(p12,
p3,
ncol = 2,
rel_widths = c(2, 1))
final_plot