简体   繁体   English

基于重量着色网络x边缘

[英]Coloring networkx edges based on weight

How do I change the color of the edges in a graph in networkx based on the weights of those edges? 如何根据这些边的权重更改networkx中图形中边的颜色?

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)

Scaling the edge weights to be between 0 and 1 doesn't change anything. 将边权重缩放到0到1之间不会改变任何东西。

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. 我不确定上面的代码与相关问题中的代码有什么不同,除了我没有为draw_networkx使用循环,因为我没有为图形设置动画。

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

Just modified an example code from networkx that plots a simple graph. 刚刚修改了networkx中的一个示例代码,该代码绘制了一个简单的图形。

A simpler use in networkx 2.2 as seen in this example . 在本例中可以更简单地使用networkx 2.2

And using the code used by the answer above by Vikram: 并使用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

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM