Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
450 views
in Technique[技术] by (71.8m points)

python - 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?

The following code just gives all black edges,even though the colormap is jet! (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)

Scaling the edge weights to be between 0 and 1 doesn't change anything.

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
    #!/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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...