4

是否可以使用拼凑而成的“主要”标题下方和情节标题上方的图例?

library(ggplot2)
library(patchwork)

p1 <- ggplot(mtcars, aes(disp, wt, color = factor(gear))) + 
    geom_point() + 
    labs(title = "first plot title")
p2 <- ggplot(mtcars, aes(drat, qsec, color = factor(gear))) + 
    geom_point() + 
    labs(title = "second plot title")

(p1+p2) + 
    plot_layout(guides = "collect") + 
    plot_annotation(title = "main title") & 
    theme(legend.position = "top")

在此处输入图像描述

4

1 回答 1

2

有点破解,提取图例然后将其绘制在顶部:

# get the legend
l <- cowplot::get_legend(p1 + theme(legend.position = "top"))

(cowplot::plot_grid(l) / (p1 + p2)) + 
  plot_layout(heights = unit(c(1, 5), "cm")) +
  plot_annotation(title = "main title") &
  theme(legend.position = "none")

在此处输入图像描述

于 2021-01-15T10:04:41.143 回答