我正在尝试为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, pos, 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, pos, edge_color=colorList, edge_cmap = plt.cm.jet)
plt.colorbar(edges)
这给了我一个错误TypeError: You must first set_array for mappable
将edge_color更改为weights_list我得到以下图片:
答案 0 :(得分:4)
您似乎正在获取节点的colormap / 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,pos,node_color='k', with_labels=False)
edges = nx.draw_networkx_edges(G,pos,edge_color=colors,width=4,
edge_cmap=plt.cm.Blues)
plt.colorbar(edges)
plt.axis('off')
答案 1 :(得分:0)
我知道这是一个旧的,但我花了一些时间弄清楚了这一点,也许它对某人还是有用的。
nx.draw_networkx_edges
返回
matplotlib.collection.LineCollection
如果没有箭头。
返回
list of matplotlib.patches.FancyArrowPatch
如果有箭头。
对于我的具体情况,只有将箭头设置为False时,我才能得到Aric答案中的颜色条:
edges = nx.draw_networkx_edges(G, edge_color=colors, arrows=False)
plt.colorbar(edges)