首页 > 解决方案 > NetworkX:基于节点颜色的颜色代码边缘

问题描述

我创建了一个 networkX 加权图(有关代码,请参阅此问题),我想根据节点颜色对边缘进行颜色编码。如果两个节点的颜色相同并且相互连接,我希望它们的边缘颜色是一种颜色,比如红色。此外,如果节点的颜色不同但连接在一起,我希望它们是不同的颜色,比如蓝色。有没有办法我可以做到这一点?

边的代码如下:

for edge in G.edges():
    source, target = edge
    rad = 0.35
    arrowprops=dict(lw=G.edges[(source,target)]['weight'],
                    arrowstyle="-",
                    color='blue',
                    connectionstyle=f"arc3,rad={rad}",
                    linestyle= '-',
                    alpha=0.6)
    ax.annotate("",
                xy=pos[source],
                xytext=pos[target],
                arrowprops=arrowprops
               )

标签: pythonmatplotlibnetworkx

解决方案


这是一个给你的例子。如果节点不同,则边缘为红色,如果它们相同,则为绿色。

import numpy as np
import networkx as nx
import matplotlib.pyplot as plt

G = nx.fast_gnp_random_graph(10, 0.5)

node_colors = [random.choice(["blue", "black"]) for node in G.nodes()]
edge_colors = [
    "green" if node_colors[edge[0]] == node_colors[edge[1]] else "red"
    for edge in G.edges()
]

plt.figure()
coord = nx.spring_layout(G, k=0.55, iterations=20)
nx.draw_networkx_nodes(G, coord, node_color=node_colors)
nx.draw_networkx_edges(G, coord, edge_color=edge_colors)

结果图


推荐阅读