2

I need to plot some simple line plots along with an image. However, the image's left and right side need to align to both the left and right end of the line plot.

My code produces the following graph: enter image description here

However, I need the graph to look like this (dash lines on the edge only for reference): enter image description here

As such, I need a way to both move and scale the image along the x-axis to accomplish this.

The code I am currently using is:

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")
pogibas
  • 27,303
  • 19
  • 84
  • 117
Mario Reyes
  • 385
  • 1
  • 2
  • 13

1 Answers1

1

We need to separate the legend from the plot to make it easier for alignment. The procedure is similar to this 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

enter image description here

Tung
  • 26,371
  • 7
  • 91
  • 115