2013-07-13 80 views
5

如何根據這些邊的權重更改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
#!/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的示例代碼,該代碼繪製了一個簡單的圖。

相關問題