我想在networkx图中获取边缘的颜色条.这是一段代码片段
import networkx as nx
import matplotlib.colors as colors
import matplotlib.cm as cmx
n = 12 # Number of clusters
w = 21 # Number of weeks
m = Basemap(
projection='merc',ellps = 'WGS84',llcrnrlon=-98.5,llcrnrlat=25,urcrnrlon=-60,urcrnrlat=50,lat_ts=0,resolution='i',suppress_ticks=True)
mx,my = m(list(ccentroids['lon']),list(ccentroids['lat']))
# The NetworkX part
# put map projection coordinates in pos dictionary
G = nx.DiGraph()
G.add_nodes_from(range(n))
for i in range(n):
for j in range(n):
if P_opt[i,j] > 0.5 and i != j:
G.add_edge(i,j,weight = P_opt[i,j])
pos = {i : (mx[i],my[i]) for i in range(n)}
# Add a color_map for the edges
jet = cm = plt.get_cmap('jet')
cNorm = colors.Normalize(vmin=0,vmax=np.max(P_opt))
scalarMap = cmx.ScalarMappable(norm=cNorm,cmap=jet)
colorList = []
weights_list = []
for i in G.edges():
a,b = i
colorVal = scalarMap.to_rgba(G.edge[a][b]['weight'])
colorList.append(colorVal)
weights_list.append(G.edge[a][b]['weight'])
plt.clf()
fig = plt.figure()
ax = fig.add_subplot(111,axisbg='w',frame_on=False)
fig.set_size_inches(18.5,10.5)
# draw the network
nodes = nx.draw_networkx_nodes(G,pos,node_size=100,node_color=q[:,t],cmap = plt.cm.jet,font_size=8,with_labels=False,label='Cluster centroids')
edges = nx.draw_networkx_edges(G,edge_color=colorList)
m.drawcountries()
m.bluemarble()
这给了我以下图像:
现在我想为边缘添加一个颜色条.我尝试过像这样的事情,
plt.sci(edges)
edges.set_array(np.array(weights_list))
plt.colorbar(shrink = 0.8)
这给了我一个像这样的图像:
箭头和边缘的颜色似乎不同.我怎么能纠正这个?谢谢.
edges = nx.draw_networkx_edges(G,edge_color=colorList,edge_cmap = plt.cm.jet)
plt.colorbar(edges)
这给了我一个错误TypeError:你必须首先set_array为mappable
将edge_color更改为weights_list我得到以下图片:
最佳答案
看来你正在获得节点的colomap / colorbar.以下是如何设置色彩映射并为边缘颜色绘制颜色条:
![import networkx as nx
import matplotlib.pyplot as plt
G = nx.star_graph(20)
pos = nx.spring_layout(G)
colors = range(20)
nodes = nx.draw_networkx_nodes(G,node_color='k',with_labels=False)
edges = nx.draw_networkx_edges(G,edge_color=colors,width=4,edge_cmap=plt.cm.Blues)
plt.colorbar(edges)
plt.axis('off')