基于重量着色网络x边缘

时间:2013-07-13 16:41:13

标签: python matplotlib networkx

如何根据这些边的权重更改networkx中图形边缘的颜色?

以下代码仅提供所有黑色边缘,即使色彩图是喷射的! (picture)

 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之间不会改变任何内容。

我不确定上述代码与related question中的代码有什么不同,只是我没有为draw_networkx使用循环,因为我没有动画图形。

2 个答案:

答案 0 :(得分:3)

    #!/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

刚修改了一个简单图形的网络示例代码。

答案 1 :(得分:0)

networkx 2.2中使用更简单,如in this example所示。

并使用上述Vikram答案使用的代码:

import matplotlib.pyplot as plt
import matplotlib.colors as colors
import matplotlib.cm as cmx
import numpy as np

import networkx as nx

G=nx.path_graph(8)
#Number of edges is 7
values = range(7)
nx.draw(G, edge_color=values, cmap=plt.cm.jet)
plt.show() # display

enter image description here