根据重量为networkx边缘着色 [英] Coloring networkx edges based on weight
本文介绍了根据重量为networkx边缘着色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何根据网络边缘的权重更改其边缘颜色?
How do I change the color of the edges in a graph in networkx based on the weights of those edges?
即使颜色表是黑色的,下面的代码也只给出了所有黑色边缘!
The following code just gives all black edges,even though the colormap is jet!
nx.draw_networkx(g,pos=pos,with_labels=True,edge_colors=[g[a][b]['weight'] for a,b in g.edges()], width=4,edge_cmap = plt.cm.jet)
将边缘权重缩放到0到1之间不会改变任何内容.
Scaling the edge weights to be between 0 and 1 doesn't change anything.
我不确定上面的代码与相关问题中的代码有何不同我没有为draw_networkx
使用循环,因为我没有为图形设置动画.
I'm not sure how the above code differs from that in a related question except that I don't use a loop for draw_networkx
because I'm not animating the graph.
推荐答案
#!/usr/bin/env python
"""
Draw a graph with matplotlib.
You must have matplotlib for this to work.
"""
try:
import matplotlib.pyplot as plt
import matplotlib.colors as colors
import matplotlib.cm as cmx
import numpy as np
except:
raise
import networkx as nx
G=nx.path_graph(8)
#Number of edges is 7
values = range(7)
# These values could be seen as dummy edge weights
jet = cm = plt.get_cmap('jet')
cNorm = colors.Normalize(vmin=0, vmax=values[-1])
scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=jet)
colorList = []
for i in range(7):
colorVal = scalarMap.to_rgba(values[i])
colorList.append(colorVal)
nx.draw(G,edge_color=colorList)
plt.savefig("simple_path.png") # save as png
plt.show() # display
只需修改networkx的示例代码即可绘制简单图形.
Just modified an example code from networkx that plots a simple graph.
这篇关于根据重量为networkx边缘着色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文