[英]How to add a simple "colorbar" to a network-graph plot in python?
我想知道如何簡單地向我的 plot 添加顏色條。我必須遵循代碼,它通過讀取 gml 文件繪制圖形。 我有一組數字分配給邊緣,作為它們的 colors,我只想在 plot 旁邊看到一個顏色條,這樣我就可以分析 colors。當我添加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
]
]
由於我沒有您的數據,我在networx主頁上使用了這個簡單的例子 。 但是在你的代碼中使用它應該是微不足道的。
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
有點可悲。
老問題,但對於現在正在尋找的人來說,您還可以分別使用nx.draw.networkx_nodes
和nx.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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.