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

如何用patchwork的inset_element()实现分层面板对应嵌入子图?

分面图中为每个分面嵌入对应子图的高效实现方法

你可以借助gggrid包实现该需求,无需手动拆分数据集再拼接,具体步骤如下:

1. 安装并加载依赖包

install.packages("gggrid")
library(tidyverse)
library(patchwork)
library(gggrid)

2. 定义子图绘制函数

该函数会自动识别当前分面的am值,筛选对应数据生成密度子图:

draw_inset <- function(data) {
  am_val <- unique(data$am)
  sub_plot <- ggplot(data %>% filter(am == am_val), aes(hp)) +
    geom_density(aes(fill = factor(cyl), color = factor(cyl)), alpha = 0.3) +
    theme_void() +
    theme(legend.position = "none")
  
  grid::grid.draw(ggplotGrob(sub_plot))
}

3. 生成带嵌入子图的分面主图

通过geom_grid()将子图嵌入对应分面的指定位置:

p1 <- ggplot(mtcars, aes(cyl, mpg)) + 
  geom_point(color = "red") +
  facet_wrap(~am) +
  geom_grid(data = mtcars, mapping = aes(), draw = draw_inset,
            x = unit(0.75, "npc"), y = unit(0.75, "npc"),
            width = unit(0.4, "npc"), height = unit(0.4, "npc"))
p1

如果偏好更底层的布局控制,也可以使用gtable包手动调整分面布局,但gggrid的方式更简洁高效,无需处理复杂的表格结构逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 07:13:28