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

如何用单个DataFrame在ggraph中绘制多张关系图?

解决方案:用分组映射实现ggraph多图布局

你可以通过**dplyr分组 + purrr批量绘图**的方式实现按Country拆分的多图效果,ggraph本身没有内置分面函数,但结合tidyverse工具可以轻松实现需求。以下是完整实现代码:

1. 原始数据集

df <- data.frame( 
  "PersonName1" = c("F","H","H","H","K","K","K","K","N","N","G","N","N","N","K","G","K"), 
  "PersonName2" = c("G","G", "F","N","N","F","H","G","G","F","H","F","H","F","F","F","H"), 
  "P" = c(0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0, 0,0.5,0,0.5,0.5,0.5,0.5), 
  "Country" = c("UK","UK","UK","UK","UK","UK","UK","UK","UK","UK","UK","Rwanda","Rwanda","Vietnam","Vietnam","Vietnam","Vietnam")) 

2. 完整实现代码

library(ggraph)
library(tidygraph)
library(cowplot)
library(dplyr)
library(purrr)

# 定义绘图函数:输入单个分组的数据,返回对应的ggraph
plot_graph <- function(group_data) {
  group_data %>%
    as_tbl_graph() %>%
    activate(edges) %>%
    filter(P > 0) %>%
    activate(nodes) %>%
    ggraph(layout = 'circle') +
    geom_node_text(aes(label = name), size = 6, 
                   check_overlap = TRUE) + 
    geom_edge_link2(aes(width = after_stat(index)), color = "red", alpha = 0.5) +
    geom_node_point(size = 15)  +
    scale_edge_width(range = c(0, 10), guide = 'none') +
    coord_cartesian(xlim = c(-1.5, 1.5), ylim = c(-1.5, 1.5)) +
    theme_void() +
    labs(title = unique(group_data$Country)) # 添加分组标题
}

# 按Country分组,批量生成所有图
country_plots <- df %>%
  group_split(Country) %>%
  map(plot_graph)

# 生成自定义图例(复用你的代码)
data.frame(lg1 = "Y", lg2 = "X" , P = 0.5) %>% 
  as_tbl_graph() %>%
  activate(edges) %>%
  filter(P > 0) %>%
  activate(nodes) %>%
  ggraph(layout = 'circle') +
  geom_node_text(aes(label = name), size = 4, nudge_y = -0.15) +
  geom_edge_link2(aes(width = after_stat(index)), color = "grey", alpha = 0.5) +
  geom_node_point(size = 10) +
  scale_edge_width(range = c(0, 5), guide = 'none') +
  coord_cartesian(xlim = c(-1.5, 1.5), ylim = c(-1.5, 1.5)) +
  theme_void() -> p_lg

p_lg <- ggdraw(p_lg) +
  draw_label("显著性", y = 0.66, size = 14) +
  draw_label("X显著高于Y", y = 0.62, size = 10) +
  draw_label("(p < 0.05)",  y = 0.54, size = 10)

# 拼接所有图和图例:先把多图拼成一行,再和图例组合
combined_plots <- plot_grid(plotlist = country_plots, ncol = 3)
final_plot <- plot_grid(combined_plots, p_lg, ncol = 2, widths = c(9, 1))

# 查看最终图
print(final_plot)

关键步骤说明

  • 自定义绘图函数:plot_graph封装了单张图的绘制逻辑,输入单个国家的子数据集,输出带标题的ggraph。
  • 批量生成图:用group_split把原数据按Country拆分成多个子数据集,再用map批量调用绘图函数,得到所有国家的图列表。
  • 拼接布局:用cowplot::plot_grid先把多图横向拼接,再和自定义图例组合,实现示例图的布局。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 14:10:38