如何实现弦图单起源区域高亮、其余区域灰色淡化?
解决方案:聚焦特定起源区域的弦图实现
核心思路
针对每个起源区域单独生成弦图时,将非目标起源区域的所有关联路径及节点设置为灰色,仅保留目标起源的节点和关联路径为彩色,以此突出聚焦效果。
示例代码实现(基于circlize包)
假设你的数据框名为df,包含origin(起源区域)、destination(目的地区域)、count(流量/数量)三列。
1. 准备数据与颜色映射
library(circlize) library(dplyr) # 示例数据 df <- data.frame( origin = c("Asia", "Asia", "Europe", "Europe", "Africa", "Africa"), destination = c("Europe", "Africa", "Asia", "Africa", "Asia", "Europe"), count = c(20, 15, 18, 12, 10, 8) ) # 定义基础颜色:目标区域用彩色,其余用灰色 origin_list <- unique(df$origin) color_map <- setNames(rep("gray", length(origin_list)), origin_list)
2. 批量生成聚焦弦图
for(target_origin in origin_list) { # 更新颜色映射:仅目标起源区域保留彩色,这里用红色示例,可自定义 color_map[target_origin] <- "#E63946" # 生成矩阵格式数据(circlize要求的输入格式) mat <- df %>% mutate( # 将非目标起源的行标记为灰色组 origin_group = ifelse(origin == target_origin, origin, "Other"), destination_group = ifelse(origin == target_origin, destination, "Other") ) %>% group_by(origin_group, destination_group) %>% summarise(total = sum(count), .groups = "drop") %>% pivot_wider(names_from = destination_group, values_from = total, values_fill = 0) %>% column_to_rownames("origin_group") %>% as.matrix() # 绘制弦图 pdf(paste0("chord_focus_", target_origin, ".pdf"), width = 8, height = 8) circos.clear() chordDiagram( mat, grid.col = c(color_map[target_origin], "gray"), # 节点颜色 col = function(region, value) { # 路径颜色:仅目标起源的路径用彩色,其余灰色 if(grepl(target_origin, region)) color_map[target_origin] else "gray" }, annotationTrack = "grid", preAllocateTracks = list(track.height = 0.1) ) circos.trackPlotRegion(track.index = 1, panel.fun = function(x, y) { circos.text(CELL_META$xcenter, CELL_META$ylim[1], CELL_META$sector.index, facing = "clockwise", niceFacing = TRUE, adj = c(0, 0.5)) }, bg.border = NA) title(main = paste("Focus on Origin:", target_origin)) dev.off() }
3. 关键细节说明
- 数据分组处理:将非目标起源的所有行合并为
Other组,绘图时统一显示为灰色节点和路径。 - 颜色动态调整:循环中每次更新
color_map,确保仅当前目标起源区域使用彩色。 - 路径颜色控制:通过
col参数的自定义函数,判断路径是否关联目标起源,分配对应颜色。
替代方案(基于chorddiag包)
如果偏好交互式弦图,可使用chorddiag包实现类似效果:
library(chorddiag) for(target_origin in origin_list) { # 构建颜色向量 node_colors <- ifelse(names(color_map) == target_origin, "#E63946", "gray") # 生成矩阵 mat <- xtabs(count ~ origin + destination, data = df) # 将非目标起源的行和列设置为半透明灰色(或直接合并) mat[rownames(mat) != target_origin, ] <- mat[rownames(mat) != target_origin, ] * 0.3 # 绘制交互式弦图 chorddiag(mat, groupColors = node_colors, groupnamePadding = 20) }
内容的提问来源于stack exchange,提问作者msug
相关产品推荐
相关产品推荐

