2016-07-22 59 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)