首页 > 解决方案 > 使用 networkx 绘制图形时,如何在边缘使用颜色?

问题描述

使用networkx绘图时,我将如何使用颜色值来处理一组边缘?

例如,这绘制了 3 个节点,

edges = pd.DataFrame({'node_1': [1, 2, 3],
                      'node_2': [2, 3, 1],
                      'edge_id': [5, 4, 6]})

G = nx.from_pandas_edgelist(edges, 'node_1', 'node_2', True, nx.Graph())
nx.draw(G, node_size = 100)
plt.draw()
plt.show()

我如何能够使用这样的数据在边缘着色?



draw = pd.DataFrame({'edge_id': [5, 4, 6],
                    'edge_colour': ['AE6017', 'F15B2E', 'F15B2E']})

标签: pythonnetworkx

解决方案


您可以分步绘制边和节点。在那里,您可以为其中任何一个提供颜色列表。为了分别绘制它们,首先需要计算它们的位置。对于大多数图表,最佳布局是通过调用spring_layout.

演示代码:

import pandas as pd
import matplotlib.pyplot as plt
import networkx as nx

edges = pd.DataFrame({'node_1': [1, 2, 3],
                      'node_2': [2, 3, 1],
                      'edge_id': [5, 4, 6]})
G = nx.from_pandas_edgelist(edges, 'node_1', 'node_2', True, nx.Graph())

pos = nx.spring_layout(G)
nx.draw_networkx_nodes(G, pos, node_size = 100, node_color='deepskyblue')
cmap_colors = plt.cm.Set1.colors
edge_colors = [cmap_colors[edge_ind %  len(cmap_colors)] for edge_ind in range(len(G.edges))]
nx.draw_networkx_edges(G, pos, width=1.0, edge_color=edge_colors)

plt.show()

结果

或者,您可以替换nx.drawnx.draw_networkx. nx.draw_networkx类似于nx.draw,但允许更多选项。如果需要,您可以给出位置,如果没有,它们会自动计算。它接受与edge_color=...相同nx.draw_networkx_edges


推荐阅读