7

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

下面的代码只是给出了所有的黑色边缘,即使颜色图是喷射的!(图片)

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

我不确定上面的代码与相关问题中的代码有何不同,除了我不使用循环,draw_networkx因为我没有为图表设置动画。

4

2 回答 2

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

刚刚修改了来自 networkx 的示例代码,它绘制了一个简单的图表。

于 2013-07-14T08:39:54.483 回答
1

一个更简单的用法,networkx 2.2本例所示

并使用维克拉姆上述答案使用的代码:

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

在此处输入图像描述

于 2018-10-25T05:59:53.317 回答