Draw different color for nodes in networkx based on their node value

后端 未结 2 1096
傲寒
傲寒 2020-12-04 19:36

I have a large graph of nodes and directed edges. Furthermore, I have an additional list of values assigned to each node.

I now want to change the color of each node

2条回答
  •  再見小時候
    2020-12-04 19:51

    import networkx as nx
    import numpy as np
    import matplotlib.pyplot as plt
    
    G = nx.Graph()
    G.add_edges_from(
        [('A', 'B'), ('A', 'C'), ('D', 'B'), ('E', 'C'), ('E', 'F'),
         ('B', 'H'), ('B', 'G'), ('B', 'F'), ('C', 'G')])
    
    val_map = {'A': 1.0,
               'D': 0.5714285714285714,
               'H': 0.0}
    
    values = [val_map.get(node, 0.25) for node in G.nodes()]
    
    nx.draw(G, cmap=plt.get_cmap('viridis'), node_color=values, with_labels=True, font_color='white')
    plt.show()
    

    yields


    The numbers in values are associated with the nodes in G.nodes(). That is to say, the first number in values is associated with the first node in G.nodes(), and similarly for the second, and so on.

提交回复
热议问题