Search code examples
python-3.xnetworkx

how to draw each node by networkx?


I know there's a function, nx.draw_networkx_nodes(G, pos, node_size=200, node_color='#00b4d9') can draw all nodes in the network. However, each of my node have a different color,dataset and code like that,

df_name = ['A','B','C','D','E']
val_idx = [1,2,3,4,5]
pred_pca_spec = [1,2,0,1,4]

#Note! below is rgb color value of each sample
val_rgb = [[130,  89,  34],[170, 133,  75],[126,  85,  17],[120,  81,  37],[162, 126,  65]]  

G = nx.Graph()
G.add_node('no.1')
pos = nx.spring_layout(G)
for i in range(0, len(df_name)):
    if pred_pca_spec[i] == 1:      
        G.add_edge('no.1', int(val_idx[i])) # I want to set color in this line at same time,like
######G.add_edge('no.1', node_value = int(val_idx[i]), node_color = '#%02x%02x%02x' % tuple(val_rgb[i]))#####
nx.draw_networkx(G)
plt.show()

Is there some function can achieve it? Note!Because dataset are dyes textile samples so I must show true color of them, only can use the rgb color space, not

colors = ["r", "g", "b", "y", "w"]

please!


Solution

  • I'm still not sure, what exactly your problem is or where you struggle or why you want to add the color within the for loop. However, I hope the following code solves your problem. Using Color using RGB value in Matplotlib I casted your RGB to values between 0 and 1.

    import networkx as nx
    import matplotlib.pylab as plt
    
    df_name = ["A", "B", "C", "D", "E"]
    val_idx = [1, 2, 3, 4, 5]
    pred_pca_spec = [1, 2, 0, 1, 4]
    val_rgb = [[130, 89, 34],
               [170, 133, 75],
               [126, 85, 17],
               [120, 81, 37],
               [162, 126, 65], ]
    
    val_rgb = [(r / 255, g / 255, b / 255) for r, g, b in val_rgb]
    
    G = nx.Graph()
    G.add_node('no.1')
    G.nodes['no.1']["color"] = tuple(val_rgb[0])  # or whatever color you like
    pos = nx.spring_layout(G)
    for i in range(0, len(df_name)):
        if pred_pca_spec[i] == 1:
            node = int(val_idx[i])
            G.add_edge('no.1', node)
            G.nodes[node]["color"] = val_rgb[i]
    
    nx.draw_networkx(G, node_color=[G.nodes[node]["color"] for node in G])
    plt.show()
    

    Result

    enter image description here