2016-07-22 25 views
3

我有一個networkx圖的圖,其中邊緣顏色取決於使用以下代碼(與a_netw nx.Graph)分配給相應邊的權重:向網絡添加圖例以解釋節點的着色

a_netw_edges = a_netw.edges() 
a_netw_weights = [a_netw[source][dest]['weight'] for source, dest in a_netw_edges] 
a_netw_colors = [plt.cm.Blues(weight*15) for weight in a_netw_weights] 
nx.draw_networkx(a_netw, edges=a_netw_edges, width=1, edge_color=a_netw_colors) 

對於這個圖表,我想添加一個圖例,使權重和顏色之間的連接明確;例如在使用pcolor的熱圖中。

雖然我如何開始一個粗略的想法:

fig, axes = plt.subplots(nrows=2) 
nx.draw_networkx(a_netw, edges=a_netw_edges, width=1, edge_color=a_netw_colors, ax=axes[0]) 
axes[0].get_xaxis().set_visible(False) 
axes[0].get_yaxis().set_visible(False) 
gradient = np.linspace(0, 1, 256) 
gradient = np.vstack((gradient, gradient)) 
axes[1].imshow(gradient, aspect=3, cmap=plt.cm.Blues) 
axes[1].get_yaxis().set_visible(False) 
plt.tight_layout() 

我不知道該怎麼做以下步驟:

  1. 添加在相關軸正確蜱得到與權重連接。
  2. 垂直而不是水平地繪製它。
+0

請所有相關的導入語句添加到代碼的頂部,並提供示例數據,可能在一個小例子,網絡足以重現你正在嘗試做的形式。 – jlarsch

回答

2

我建議你使用colorbar()命令,如下所示。我正在提供一個示例圖,看看它是否有意義?

enter image description here

import networkx as nx 
import matplotlib.pyplot as plt 

#generate a graph with weights 
a_netw=nx.Graph() 
a_netw.add_edge('a','b',weight=6) 
a_netw.add_edge('a','c',weight=2) 
a_netw.add_edge('c','d',weight=1) 
a_netw.add_edge('c','e',weight=7) 
a_netw.add_edge('c','f',weight=9) 
a_netw.add_edge('a','d',weight=3) 

#creating a color list for each edge based on weight 

a_netw_edges = a_netw.edges() 
a_netw_weights = [a_netw[source][dest]['weight'] for source, dest in a_netw_edges] 

#scale weights in range 0-1 before assigning color 
maxWeight=float(max(a_netw_weights)) 
a_netw_colors = [plt.cm.Blues(weight/maxWeight) for weight in a_netw_weights] 


#suppress plotting for the following dummy heatmap 
plt.ioff() 

#multiply all tuples in color list by scale factor 
colors_unscaled=[tuple(map(lambda x: maxWeight*x, y)) for y in a_netw_colors] 
#generate a 'dummy' heatmap using the edgeColors as substrate for colormap 
heatmap = plt.pcolor(colors_unscaled,cmap=plt.cm.Blues) 

#re-enable plotting 
plt.ion() 

fig,axes = plt.subplots() 
nx.draw_networkx(a_netw, edges=a_netw_edges, width=10, edge_color=a_netw_colors, ax=axes) 
axes.get_xaxis().set_visible(False) 
axes.get_yaxis().set_visible(False) 

#add colorbar 
cbar = plt.colorbar(heatmap) 
cbar.ax.set_ylabel('edge weight',labelpad=15,rotation=270) 
相關問題