r - 使用 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")
解决方案
这是使用该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))
推荐阅读
- c# - 为什么这个异步程序不交错输出?
- sparql - SPARQL 在内存中查询 GRAPH 联合?
- android - CameraX - 无法配置相机
- twitter-bootstrap - 如何使用引导程序在 jsf 中使面板标题可点击
- python - 导入 Pandas 时出现问题
- css - 如何在滚动的 flexbox 父级中显示最后一个子级的下边距?
- reactjs - React:将函数作为道具发送
- python - 用于图像重建的自动编码器产生带有奇怪网格的灰色图像
- matrix - JuMP目标函数中的矩阵向量积,其中矩阵是一个变量
- node.js - 如何等待从 Cloud Firestore 中获取数据,然后在 NodeJS 中返回它们?