NetworkX节点按属性设置颜色不匹配问题求助
NetworkX节点颜色与属性不匹配问题排查与解决
问题根源
颜色与属性不匹配的核心原因是节点顺序不一致:
nx.draw渲染节点时,默认遵循g.nodes()的遍历顺序- 你通过
pd.DataFrame.from_dict(dict(G.nodes(data=True)), orient='index')生成的DataFrame,其行顺序不一定和g.nodes()的顺序完全一致,导致颜色列表和节点列表错位
修复方案
修改attri_to_color函数,让颜色列表的顺序严格对应g.nodes()的遍历顺序,避免依赖DataFrame的自动排序:
def attri_to_color(G, attri_name): replace_dict = {"A": "red", "B": 'blue', "C": 'green', "D": 'purple'} # 按g.nodes()的顺序逐个获取节点属性并映射颜色 color = [replace_dict[G.nodes[node][attri_name]] for node in G.nodes()] return color
完整修正后的代码
import networkx as nx import matplotlib.pyplot as plt import pandas as pd path = "data/" df = pd.read_excel(path + "example_data_for_test1.xlsx") node_attri = pd.read_excel(path + "example_data_for_test2.xlsx") edgelist = list(zip(df["source"], df["target"], df["weight"])) node_attri = dict(zip(node_attri["city"], node_attri["type"])) g = nx.DiGraph() g.add_weighted_edges_from(edgelist, weight="weight") nx.set_node_attributes(g, node_attri, "city_type") # 修正后的颜色映射函数 def attri_to_color(G, attri_name): replace_dict = {"A": "red", "B": 'blue', "C": 'green', "D": 'purple'} color = [replace_dict[G.nodes[node][attri_name]] for node in G.nodes()] return color def draw_network(g): fig = plt.figure(1, figsize=(40, 30)) pos = nx.spring_layout(g, k=2.5, iterations=50) d = nx.degree(g) d = [(d[node] + 0.1) * 50 for node in g.nodes()] colors = attri_to_color(g, "city_type") nx.draw( g, pos=pos, node_size=d, node_color=colors, with_labels=True, edge_color="gainsboro", arrows=True, arrowsize=5, alpha=0.4, ) plt.show() draw_network(g)
额外优化提示
你也可以直接在绘图时生成颜色列表,省去单独的函数,让代码更简洁:
# 替换原colors = attri_to_color(...)这一行 replace_dict = {"A": "red", "B": 'blue', "C": 'green', "D": 'purple'} colors = [replace_dict[g.nodes[node]['city_type']] for node in g.nodes()]
这样就能确保每个节点的颜色和其city_type属性严格对应,不会出现错位问题。
内容的提问来源于stack exchange,提问作者yy w
相关产品推荐
相关产品推荐

