如何在Python的网络图中添加简单的“色条”?

9 投票
2 回答
9728 浏览
提问于 2025-05-01 14:03

我在想,怎么才能简单地给我的图加一个颜色条呢?我有一段代码,它通过读取一个gml文件来绘制图形。我有一组数字,想把它们用作边的颜色,我只想在图旁边看到一个颜色条,这样我就可以分析这些颜色。当我添加 plt.colorbar(g) 时,它给我报错。有没有办法在不经过复杂步骤的情况下,加一个颜色条呢?

H = nx.read_gml('./network1.gml')

EAM = EigenVectorCentrality( EAMatrix );

x = [];
for eam in EAM[0]:
    x.append(eam[0]);

 degs =  H.degree().values();
 plt.clf()
 g = nx.draw(H, with_labels=0, edge_color=x, node_size=70, font_size=9, width=1)
 plt.axis('equal')     
 plt.colorbar(g);
 plt.show()

这是Nerwork1.gml文件:

graph
[
   node
   [
    id 1
   ]
 node
[
    id 2
]
node
[
    id 3
]
node
[
    id 4
]
    node
[
    id 5
]
    node
[
    id 6
]
    node
[
    id 7
]
    node
[
    id 8
]
    node
[
    id 9
]
    node
[
    id 10
]
    node
[
    id 11
]
edge
[
    source 1
    target 2
]
edge
[
    source 1
    target 2
]
edge
[
    source 1
    target 3
]
edge
[
    source 1
    target 4
]
edge
[
    source 1
    target 5
]
edge
[
    source 2
    target 3
]
edge
[
    source 2
    target 4
]
edge
[
    source 2
    target 5
]
edge
[
    source 3
    target 4
]
edge
[
    source 3
    target 5
]
edge
[
    source 4
    target 5
]
edge
[
    source 6
    target 7
]
edge
[
    source 6
    target 8
]
edge
[
    source 6
    target 9
]
edge
[
    source 6
    target 10
]
edge
[
    source 7
    target 8
]
edge
[
    source 7
    target 9
]

edge
[
    source 7
    target 10
]
edge
[
    source 8
    target 9
]
edge
[
    source 8
    target 10
]
edge
[
    source 9
    target 10
]
edge
[
    source 5
    target 6
]
edge
[
    source 5
    target 11
]
 edge
 [
    source 6
    target 11
 ]
]
暂无标签

2 个回答

1

这个问题虽然老旧,但对于现在在找这个的人来说,你可以单独使用 nx.draw_networkx_nodesnx.draw_networkx_edges 这两个函数,因为这两个函数都会返回一个路径集合,这个集合可以用来给 plt.colorbar 提供数据。举个例子:

pos = nx.spring_layout(G)
pathcollection = nx.draw_networkx_nodes(G, pos, node_color=nx.get_node_attribute(G, "color"))
nx.draw_networkx_edges(G, pos)
plt.colorbar(pathcollection)
16

因为我没有你的数据,所以我用了来自networkx主页的这个简单的例子。不过,你在自己的代码里使用起来应该很简单。

import matplotlib.pyplot as plt
import networkx as nx

G=nx.star_graph(20)
pos=nx.spring_layout(G)
colors=range(20)
cmap=plt.cm.Blues
vmin = min(colors)
vmax = max(colors)
nx.draw(G, pos, node_color='#A0CBE2', edge_color=colors, width=4, edge_cmap=cmap,
           with_labels=False, vmin=vmin, vmax=vmax)
sm = plt.cm.ScalarMappable(cmap=cmap, norm=plt.Normalize(vmin = vmin, vmax=vmax))
sm._A = []
plt.colorbar(sm)
plt.show()

这样做是可以的,但我同意,nx.draw返回None确实有点让人失望。

撰写回答