使用R/ggraph为环形树状图按组着色线条遇问题求助
问题解决:ggraph环形树状图按边属性着色
错误原因
出现attempt to replicate an object of type 'closure'错误的核心原因:直接写colour=colors时,R会把colors识别为内置的colors()函数(返回系统可用颜色列表的函数),而非你edges数据中自定义的colors列。要将数据列映射到图形美学属性,必须把参数放入aes()内部。
修改方案
1. 修正边着色的映射逻辑
将geom_edge_diagonal(colour=colors)修改为geom_edge_diagonal(aes(colour = colors)),让gggraph读取igraph对象中存储的边colors属性,实现动态着色。
2. 匹配颜色比例尺类型
你的colors列是离散分类值(color1/color2等),而非连续数值,因此需要把用于连续数据的scale_edge_colour_distiller(palette = "RdPu")替换为离散手动颜色映射器scale_edge_colour_manual,指定每个分类对应的实际颜色。
3. 修复顶点分组的匹配逻辑(原代码潜在问题)
原代码中match函数的第三个参数属于冗余错误,修正顶点分组的赋值语句:
vertices$group <- edges$from[match(vertices$name, edges$to)] # 补充根节点origin的分组值 vertices$group[vertices$name == "origin"] <- "origin"
完整修改代码
library(ggraph) library(igraph) library(tidyverse) library(RColorBrewer) d1 = read.csv("~/data1.csv", sep=",") d2 = read.csv("~/data2.csv", sep=",") edges=rbind(d1, d2) # 创建顶点数据框 vertices = data.frame( name = unique(c(as.character(edges$from), as.character(edges$to))) , value = runif(78) ) # 修正顶点分组逻辑 vertices$group <- edges$from[match(vertices$name, edges$to)] vertices$group[vertices$name == "origin"] <- "origin" # 标签角度与对齐设置 vertices$id=NA myleaves=which(is.na(match(vertices$name, edges$from))) nleaves=length(myleaves) vertices$id[ myleaves ] = seq(1:nleaves) vertices$angle= 90 - 360 * vertices$id / nleaves vertices$hjust<-ifelse( vertices$angle < -90, 1, 0) vertices$angle<-ifelse(vertices$angle < -90, vertices$angle+180, vertices$angle) # 创建图对象 mygraph <- graph_from_data_frame( edges, vertices=vertices ) # 绘图:核心修改边着色逻辑 ggraph(mygraph, layout = 'dendrogram', circular = TRUE) + geom_edge_diagonal(aes(colour = colors)) + # 关键:将colour放入aes映射数据列 # 手动指定分类对应的实际颜色,可按需调整 scale_edge_colour_manual(values = c( "color1" = "#a6cee3", "color2" = "#1f78b4", "color3" = "#b2df8a", "color4" = "#33a02c" )) + geom_node_text(aes(x = x*1.12, y=y*1.12, filter = leaf, label=name, angle = angle, colour=group, hjust=hjust), size=6) + geom_node_point(aes(filter = leaf, x = x*1.07, y=y*1.07, colour=group, alpha=.2, size=2)) + scale_colour_manual(values= rep( brewer.pal(7,"Paired") , 30)) + scale_size_continuous( range = c(0.1,17) ) + theme_void() + theme( legend.position="none", plot.margin=unit(c(0,0,0,0),"cm"), ) + expand_limits(x = c(-1.3, 1.3), y = c(-1.3, 1.3))
关键说明
- 所有需要绑定数据列的美学属性(颜色、大小、形状等),必须放在
aes()内部,否则R会将其视为固定值或内置函数处理。 - 边的颜色比例尺需与数据类型匹配:离散分类用
scale_edge_colour_manual,连续数值用scale_edge_colour_distiller或scale_edge_colour_continuous。
内容的提问来源于stack exchange,提问作者Beatdown
相关产品推荐
相关产品推荐

