python - 使用 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']})
解决方案
您可以分步绘制边和节点。在那里,您可以为其中任何一个提供颜色列表。为了分别绘制它们,首先需要计算它们的位置。对于大多数图表,最佳布局是通过调用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.draw
为nx.draw_networkx
. nx.draw_networkx
类似于nx.draw
,但允许更多选项。如果需要,您可以给出位置,如果没有,它们会自动计算。它接受与edge_color=...
相同nx.draw_networkx_edges
。
推荐阅读
- c# - 如何将密码添加到使用 c# 从报表服务器生成的 Excel 文件中?
- javascript - 如何解析角度或javascript中的特定对象?
- javascript - 使用 Nodejs 编辑页面图像上传概念
- prolog - Prolog 列表表示图遍历
- c# - 使用 itextsharp 在 PDF 中的图像上显示文本
- php - Wordpress admin-ajax 不适用于来自其他国家/地区的 VPN/访问
- c# - 指定 .runsettings 文件时无法使用 vstest.console.exe - MS 测试
- android - 在 Android 中使用 Buttons 和 FragmentManager
- node.js - 检查二进制数据文件类型是否为PDF?
- laravel - Laravel Eloquent Accessor 奇怪的问题