【问题标题】:Set node color based on attribute根据属性设置节点颜色
【发布时间】:2020-06-03 23:20:25
【问题描述】:

我用默认的蓝色节点构建了一个直接图,如下图所示。

每个节点都是从“节点”类创建的对象,每个节点都具有“状态”属性,该属性可以具有以下值之一:{-1, 0, 1}

我想根据各自的状态值在下图中显示不同的节点颜色,例如,-1:红色、0:黑色和 1:蓝色。

我该怎么做呢?

【问题讨论】:

    标签: python python-3.x graph networkx graph-theory


    【解决方案1】:

    我们以下面的随机图为例:

    G = nx.barabasi_albert_graph(20, 1)
    
    plt.figure(figsize=(12, 8))
    pos = nx.spring_layout(G, scale=20, k=3/np.sqrt(G.order()))
    nx.draw(G, pos=pos, with_labels=True, k=13.8, node_color='lightgreen', node_size=800)
    

    假设我们有以下字典映射状态到颜色,以及一组我将设置为节点属性的状态:

    color_state_map = {-1: 'red', 0: 'black', 1: 'blue'}
    
    states = np.random.choice([-1,0,1], size=20)
    nx.set_node_attributes(G, dict(zip(G.nodes(), states)), 'state')
    

    为了根据状态设置节点颜色,可以使用nx.draw中的node_color参数为图形的G.nodes()设置对应的节点颜色。

    plt.figure(figsize=(12, 8))
    nx.draw(G, pos=pos, 
            with_labels=True, 
            k=13.8, 
            node_color=[color_state_map[node[1]['state']] 
                        for node in G.nodes(data=True)], 
            node_size=800,
           font_color='white')
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-08
      • 1970-01-01
      • 2019-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多