用颜色条绘制无向图是可行的,但有向图的相同图失败:
def plot(G):
positions=nx.circular_layout(G)
nx.get_edge_attributes(G, 'value')
edges, weights = zip(*nx.get_edge_attributes(G, 'value').items())
edge_cmap = plt.cm.Spectral.reversed()
fig, ax = plt.subplots()
ax = nx.draw_networkx_nodes(G, positions)
ax = nx.draw_networkx_labels(G, positions)
ax = nx.draw_networkx_edges(G, positions,
edgelist=edges,
connectionstyle=f'arc3, rad = 0.25',
edge_color = weights,
edge_cmap = edge_cmap,
edge_vmin=1,
edge_vmax=5)
cbar = fig.colorbar(ax, orientation='vertical')
return fig
# toy data
df = pd.DataFrame({"source": [0, 1, 2],
"target": [2, 2, 3],
"value": [3, 4, 5]})
绘制无向图按预期工作:
G = nx.from_pandas_edgelist(df, 'source', 'target', edge_attr='value')
plot(G)
plt.show()
绘制 digrahp 返回错误:
G = nx.from_pandas_edgelist(df, 'source', 'target', edge_attr='value',
create_using=nx.DiGraph)
plot(G)
plt.show()
错误:
AttributeError: 'list' 对象没有属性 'get_array'
回答1
对于有向图,您的变量 ax=nx.draw_networkx_edges(...)
是一个箭头列表,它不是可映射的对象。但是,对于无向图,ax
是可映射的 LineCollection
。 https://networkx.org/documentation/stable/reference/generated/networkx.drawing.nx_pylab.draw_networkx_edges.html查看更多解释。要使颜色条与有向图一起工作,您可以做的一件事就是在 nx.draw_networkx_edges
中添加 arrows=False
,使 ax
变为 LineCollection
,这反过来又使创建颜色条成为可能。