如何在ggraph中实现类似ggplot的长格式数据节点着色?
用长格式数据实现ggraph环形树状图的统一着色
完全可以实现你想要的长格式数据绘图方式!核心是把igraph节点的性状数据转成长格式,再和ggraph的布局数据结合起来,这样就能像ggplot那样用color = Trait统一控制颜色了。下面是具体的实现步骤和完整代码:
library(tidyverse) library(ggraph) # 1. 构建igraph对象(和你原代码逻辑一致) iris_g <- as.igraph(as.dendrogram(hclust(dist(iris[1:4])))) xy_expand <- function(xy, expand) xy * (1 + expand / 10) ord <- match(as.numeric(V(iris_g)$label), seq_len(nrow(iris))) # 给节点添加性状和物种属性 V(iris_g)$Petal.Length <- iris$Petal.Length[ord] V(iris_g)$Petal.Width <- iris$Petal.Width[ord] V(iris_g)$Sepal.Length <- iris$Sepal.Length[ord] V(iris_g)$Sepal.Width <- iris$Sepal.Width[ord] V(iris_g)$Species <- iris$Species[ord] V(iris_g)$node_id <- seq_len(vcount(iris_g)) # 新增节点ID,用于后续数据匹配 # 2. 将节点的宽格式性状数据转为长格式 node_data <- as_tibble(V(iris_g)) %>% select(node_id, Sepal.Length, Sepal.Width, Petal.Length, Petal.Width) %>% pivot_longer(cols = -node_id, names_to = "Trait", values_to = "Value") # 3. 生成环形树状图的布局数据 layout_df <- create_layout(iris_g, layout = "dendrogram", circular = TRUE) # 4. 合并布局数据与长格式节点数据,仅保留叶子节点 plot_data <- layout_df %>% filter(leaf) %>% inner_join(node_data, by = "node_id") # 5. 绘制图形,用长格式数据统一控制颜色 ggraph(layout_df) + geom_edge_diagonal() + geom_point(data = plot_data, aes(x = xy_expand(x, Value), y = xy_expand(y, Value), color = Trait)) + # 自定义颜色映射,和你原代码的颜色保持一致 scale_color_manual(values = c( "Sepal.Length" = "red", "Sepal.Width" = "green", "Petal.Length" = "blue", "Petal.Width" = "yellow" ))
关键逻辑说明:
- 给每个节点添加
node_id是为了让布局数据和节点性状数据能准确匹配; - 用
pivot_longer把宽格式的4个性状转为Trait(性状名称)和Value(性状值)的长格式结构,这一步和你用gather处理iris数据的逻辑完全一致; - 通过
create_layout提前获取布局的坐标数据,再和长格式节点数据合并后,就能用单条geom_point调用实现所有性状点的绘制,同时用color = Trait统一控制着色。
内容的提问来源于stack exchange,提问作者gdkrmr
相关产品推荐
相关产品推荐

