Combining plots created with cowplot::ggdraw() with patchwork: consistently formatted tags?

66 views Asked by At

I am trying to combine a plot generated with ggplot with jpeg images using patchwork. Here is my current code:

# load libraries
library(ggplot2)
library(patchwork)

# generate and save dummy jpeg
jpeg::writeJPEG(matrix(.5, nrow = 533, ncol = 800), "test.jpg")

# read dummy jpeg
test_jpeg <- jpeg::readJPEG("test.jpg", native = TRUE)

# use ggdraw from cowplot to plot the image
plot_1 <- cowplot::ggdraw() + cowplot::draw_image(test_jpeg)

# get dummy plot
plot_2 <- ggplot2::ggplot() +
    geom_blank() +
    theme(aspect.ratio = 4/3)

# combine with patchwork
plot_combined <- (plot_2 + plot_1 )/plot_1  +
  plot_layout(heights = c(1, 1)) +
  plot_annotation(tag_levels = 'A') 

# save to png
ggsave(filename = "plot_combined.png",
       plot = plot_combined,
       width = 4,
       height = 4)

This results in the following output:

enter image description here

This has the following problems:

  • Tags are differently formatted. Tags for the panels containing the images are bold. [Edit: solved]
  • Tags are not horizontally aligned. [Edit: solved]
  • Heights are not identical for all panels.

I am looking for solutions to solve these problems.

Edit

I solved the different formatting by setting theme(plot.tag = element_text(face = 'plain')

I tried using background_image() from ggpubr to create the image panel.

Further, I try to specify the layout of the plot generated with patchwork specifically using the area function:

# use background_image() from ggpubr to plot the image
plot_1 <- ggplot() + ggpubr::background_image(test_jpeg) +
  theme(aspect.ratio = 2/3)

# get layout for plotting
layout <- c(
  area(t = 1, l = 1, b = 4, r = 3),
  area(t = 1, l = 4, b = 4, r = 9),
  area(t = 5, l = 1, b = 8, r = 6)
)

# combine with patchwork
plot_combined <- plot_2 + plot_1 + plot_1  +
  plot_layout(design = layout, heights = 1) +
  plot_annotation(tag_levels = 'A') +
  theme(plot.tag = element_text(face = 'plain'))

# save to png
ggsave(filename = "plot_combined_2.png",
       plot = plot_combined,
       width = 4,
       height = 4)

Resulting in the following:

enter image description here

Problems with this are:

  • Panel heights are still not identical.
  • The offset between panels and tags is not identical for the upper and lower row.
0

There are 0 answers