首页 > 解决方案 > 使用 grid.arrange 在绘图上方添加额外的空间作为标题

问题描述

我正在使用将两个图表相互叠加,并希望使用该函数grid.arrange在两个图表上方添加一个标题。draw_label但是,正如您将在下面的示例中看到的那样,标签当前位于第一个图的顶部。有没有办法在第一个情节上方添加额外的空间让我放置标题?

在此处输入图像描述

## load libraries
library(tidyverse)
library(gridExtra)

## define simple theme
theme_background <- theme(plot.background = element_rect(fill = "#232b2b", color = NA),
                          panel.background = element_rect(fill = "#232b2b", color = NA))

## render plots
p1 <- mtcars %>% 
  ggplot(aes(x = hp, y = wt)) +
  geom_point() +
  theme_background

p2 <- mtcars %>% 
  ggplot(aes(x = disp, y = wt)) +
  geom_point() +
  theme_background

## create grid object
pGrid <- grid.arrange(p1, p2, ncol = 1)

## add label to plots
ggdraw(pGrid) +
  draw_label(label = "This is a custom label that applies to both plots", 
             x = 0.01, y = 0.95, hjust = 0, vjust = 0, size = 10, lineheight = 1, color = "white")

标签: rggplot2

解决方案


这是使用该cowplot软件包的解决方案:

# 1. Use Cowplot to arrange the plots
library(cowplot)
plot_row <- plot_grid(p1, p2, ncol = 1) +
              # To remove the border between title and plots
              panel_border(color = "#232b2b")

# 2. Create the title
title <- ggdraw() + 
  draw_label(
    label    = "This is a custom label that applies to both plots",
    fontface = 'bold',
    color    = 'white',
    x        = 0,
    hjust    = 0
  ) +
  theme(
    # add margin on the left of the drawing canvas,
    # so title is aligned with left edge of first plot
    plot.background = element_rect(fill = "#232b2b", color = NA),
    plot.margin     = margin(0, 0, 0, 7)
  )

# 3. Stack everything together
plot_grid(
  title, plot_row,
  ncol        = 1,
  # rel_heights values control vertical title margins
  rel_heights = c(0.1, 1)
) +
# To remove the border between the plots
theme(plot.background = element_rect(fill = "#232b2b", color = NA)) 

              在此处输入图像描述


推荐阅读