You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用patchwork对齐轴并按比例调整大小组合ggplot2与密度图?

生态位转移可视化:散点图+边际密度图布局问题

我正在用R 4.4.2版本,结合散点图(标准化环境值)与对应变量的边际密度图做生态位转移可视化,布局类似边际直方图。使用ggplot2 3.5.1和patchwork 1.3.0组合以下图形:

  • 中心:用geom_point()绘制的2D坐标图
  • 边际:显示变量分布的水平/垂直geom_density()密度图

遇到的问题

  • 轴对齐:各图的x轴、y轴无法完美对齐
  • 相对尺寸:密度图占比过大,希望其高度约为中心图的一半
  • 边缘裁剪:密度图边缘被截断,尤其在中心图使用coord_sf()时

需求

求简洁方法实现:

  • 同步各图的坐标轴范围与刻度
  • 精确调整图尺寸(如设置中心图高度为密度图的2倍)
  • 避免密度图边缘被裁剪

我考虑过cowplot和ggpubr,但认为patchwork灵活性最强,也欢迎推荐更好的工具或思路。

期望效果参考图(来源:Barajas Barbosa et al. 2023; DOI: 10.1038/s41586-023-06305-z)


代码

加载库

library(sf)
library(dplyr)
library(ggplot2)
library(patchwork)
library(rlang)
set.seed(42)

创建模拟点数据

data <- data.frame(
  x = rnorm(200, mean = 5, sd = 2),
  y = rnorm(200, mean = 5, sd = 2)
)

points <- data.frame(
  x = rnorm(50, mean = 6, sd = 1.5),
  y = rnorm(50, mean = 6, sd = 1.5)
)

data_points <- data.frame(
  x = rnorm(100, mean = 4.5, sd = 1),
  y = rnorm(100, mean = 4.5, sd = 1)
)

创建模拟多边形(中心(5,5)周围的正方形)

poly_coords <- matrix(c(
  3, 3,
  7, 3,
  7, 7,
  3, 7,
  3, 3
), ncol = 2, byrow = TRUE)

e_poly <- st_sf(geometry = st_sfc(st_polygon(list(poly_coords))))

绘制散点图与多边形

sp <- ggplot() +
  geom_sf(data = e_poly, fill = "#3366FF", color = "black", alpha = 0.0) +
  geom_point(data = points, aes(x, y), fill = "#FFCC33",
             color = "#FFCC33", alpha = 0.5) +
  coord_sf(
    xlim = range(dplyr::pull(data, x)),
    ylim = range(dplyr::pull(data, y))
  ) +
  theme_minimal()

水平密度图

dph <- ggplot() +
  geom_density(data = points, aes(x = x), fill = "skyblue", alpha = 0.6) +
  geom_density(data = data_points, aes(x = x), fill = "#FFCC33", alpha = 0.4) +
  theme_minimal() +
  theme(axis.text.y = element_blank(), axis.ticks.y = element_blank()) +
  coord_cartesian(xlim = range(dplyr::pull(data, x))) +
  labs(y = NULL)

垂直密度图

dpv <- ggplot() +
  geom_density(data = points, aes(x = y), fill = "skyblue", alpha = 0.6) +
  geom_density(data = data_points, aes(x = y), fill = "#FFCC33", alpha = 0.4) +
  theme_minimal() +
  theme(axis.text.x = element_blank(), axis.ticks.x = element_blank()) +
  coord_cartesian(xlim = range(dplyr::pull(data, y))) +
  labs(x = NULL) +
  coord_flip()

使用patchwork组合图形

# 初始尝试的布局
layout <- c(
  patchwork::area(t = 1, l = 2, b = 1, r = 2),
  patchwork::area(t = 2, l = 2, b = 2, r = 2),
  patchwork::area(t = 2, l = 3, b = 2, r = 3)
)

# 调整后的布局(解决尺寸问题)
layout <- c(patchwork::area(t = 1, b = 1, l = 1, r = 6),
patchwork::area(t = 2, b = 6, l = 1, r = 6),
patchwork::area(t = 2, b = 6, l = 7, r = 7))

(dph + sp + dpv) + plot_layout(design = layout, guides = "collect")

# 替代方案(调整间距)
(dph + plot_spacer() + sp + dpv) +
  plot_layout(ncol = 2, widths = c(4, 1), heights = c(1, 4)) 

已实现效果参考图


内容的提问来源于stack exchange,提问作者Antony

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 00:24:52