让 ggplot2 多面板图对齐,再按实际尺寸导出

怎样把两张 ggplot2 图排齐,再按 89 毫米宽导出?

先用 patchwork 对齐两张 ggplot2 图,再用 ggsave 导出 89 × 60 毫米的 PDF,或 1,052 × 709 像素的 300 DPI PNG。

本文目录

导出的插图怎么检查?

按最终尺寸检查 PDF 里的面板字母、刻度和坐标轴标题。如果需要交位图,核对 PNG 的实际像素尺寸。示例直接用像素指定 PNG 的宽高,确保两边都达到向上取整后的要求。

两张对齐的散点图,展示 mtcars 数据中汽车重量和马力分别与油耗的关系。
下方代码使用 R 自带的 mtcars 数据生成此图。

我用 R 自带的 mtcars 数据画两张散点图,并用 patchwork 排版。如果还没安装 ggplot2 或 patchwork,请先安装。脚本会把两个文件保存到 R 当前的工作目录。

可直接运行的 R 示例

library(ggplot2)
library(patchwork)

theme_figure <- theme_classic(base_size = 7) +
  theme(plot.tag = element_text(face = "bold"))

panel_a <- ggplot(mtcars, aes(wt, mpg)) +
  geom_point(size = 1.2, colour = "#17665c") +
  labs(x = "Weight (1,000 lb)", y = "Miles per gallon") +
  theme_figure

panel_b <- ggplot(mtcars, aes(hp, mpg)) +
  geom_point(size = 1.2, colour = "#17665c") +
  labs(x = "Horsepower", y = "Miles per gallon") +
  theme_figure

figure <- (panel_a | panel_b) + plot_annotation(tag_levels = "A")
ggsave("figure.pdf", figure, width = 89, height = 60, units = "mm")
ggsave("figure.png", figure, width = 1052, height = 709, units = "px", dpi = 300)

参考资料

科研图尺寸与 DPI 计算器