2

我需要绘制一些简单的线图和图像。但是,图像的左侧和右侧需要与线图的左右端对齐。

我的代码生成以下图表: 在此处输入图像描述

但是,我需要图表看起来像这样(边缘上的虚线仅供参考): 在此处输入图像描述

因此,我需要一种沿 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")
4

1 回答 1

1

我们需要将图例与绘图分开,以便更容易对齐。该过程类似于此答案

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

在此处输入图像描述

于 2018-09-12T02:05:54.240 回答