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

Networkx绘图:如何使边标签颜色与对应边颜色保持一致?

解决边标签文本颜色匹配边颜色的问题

你遇到的错误是因为nx.draw_networkx_edge_labels的font_color参数如果要为不同边标签设置不同颜色,需要传入键为边元组、值为对应颜色的字典,而不是直接传入dict_values对象。

修改后的代码

# 获取完整的边颜色字典(键为边元组,值为颜色)
edge_colors_dict = nx.get_edge_attributes(graph, 'color')

nx.draw_networkx(graph, pos, with_labels=True, connectionstyle='arc3, rad = 0.1', edge_color=edge_colors_dict.values())

edge_labels_bidirectional = dict([((u, v,), d['initial_balance'])
                    for u, v, d in graph.edges(data=True)])

# 传入边颜色字典作为font_color参数
nx.draw_networkx_edge_labels(graph, pos, edge_labels=edge_labels_bidirectional,
                             label_pos=0.3, font_size=7, font_color=edge_colors_dict)
plt.show()

关键说明

  • 原来的colors = nx.get_edge_attributes(graph, 'color').values()只保留了颜色值,丢失了边的对应关系,而font_color需要明确每条边对应的颜色,因此必须用完整的字典。
  • 调用nx.draw_networkx时,edge_color可以接受dict_values,因为它只需要颜色序列;但draw_networkx_edge_labels的font_color在多颜色场景下必须是匹配边的字典结构。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 21:30:32