我正在使用 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")
答案 0 :(得分:1)
这是使用 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))