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

Arc Diagram中基于st_disease字段的边着色问题求助

解决Arc Diagram中按疾病字段为边着色的问题

你的问题出在两个关键点:一是没把边的颜色和st_disease字段建立映射关系,直接用了固定颜色值;二是scale_edge_color_manual里的col变量未定义,同时内部边属性的映射逻辑导致了长度不匹配的报错。

按以下步骤修改代码即可解决:

  • 在geom_edge_arc0中用aes()将edge_colour绑定到边的st_disease属性(graph_from_data_frame会自动把links里的额外列转为边属性)
  • 定义对应所有疾病类别的颜色向量,确保每个疾病都有对应颜色
  • 移除固定的edge_colour="#69b3a2"参数,让颜色映射生效

修改后的完整代码:

links <- data.frame(
source = c("Convalescent plasma", "Convalescent whole blood", "Gentamicin", "Interferon β-1a", "Lopinavir/ritonavir and recombinant IFN-β1b", "MAb114", "Plasma", "Plasma", "REGN-EB3", "Remdesivir", "Ribavirin", "Ribavirin", "Ribavirin", "Ribavirin", "Ribavirin", "Ribavirin", "Tecovirimat", "ZMapp"),
target = c("No active treatment", "No active treatment", "Doxycycline", "No active treatment", "No active treatment", "ZMapp", "No active treatment", "No active treatment", "ZMapp", "ZMapp", "No active treatment", "No active treatment", "No active treatment", "No active treatment", "No active treatment", "No active treatment", "No active treatment", "Favipiravir"),
st_disease = c("Ebola", "Ebola", "Plague", "Ebola", "MERS", "Ebola", "Lassa fever", "Lassa fever", "Ebola", "Ebola", "Nipah", "Crimean Congo Haemorrhagic Fever", "Crimean Congo Haemorrhagic Fever", "Lassa fever", "Lassa fever", "Lassa fever", "Mpox", "Ebola")
)

# 提取所有唯一疾病类别,定义对应颜色
disease_cols <- c(
  "Ebola" = "#69b3a2",
  "Plague" = "#ff7f0e",
  "MERS" = "#9467bd",
  "Lassa fever" = "#e377c2",
  "Nipah" = "#17becf",
  "Crimean Congo Haemorrhagic Fever" = "#2ca02c",
  "Mpox" = "#d62728"
)

mygraph <- graph_from_data_frame(links)
p2 <-  ggraph(mygraph, layout="linear") +
  # 用aes绑定edge_colour到st_disease属性
  geom_edge_arc0(aes(edge_colour = st_disease),
                 edge_alpha=0.3,
                 edge_width=1.5) +
  geom_node_point( color="#69b3a2", size=5, position = "identity") +
  geom_node_text( aes(label=name), repel = TRUE, size=4, color="black", nudge_y=-0.5 ,angle=70, vjust=1) +
  # 应用手动颜色映射
  scale_edge_color_manual(values = disease_cols)+
  theme_void() +
  theme(
    legend.position="none",
    plot.margin=unit(c(4,2,2,2), "cm"))+
  coord_cartesian(clip = "off")

p2

如果需要显示图例,只需将legend.position="none"改为legend.position="right"(或其他你需要的位置)即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 05:45:42