Networkx,改变节点颜色

Networkx, changing node colors

我想根据属性值更改节点的颜色。具体来说,在这种情况下,当属性 'status' 为 1 时,我希望颜色为某种颜色,而当它为 0 时,则为其他颜色。一个限制是我希望节点以点阵格式打印,我在这里使用 2d_grid_graph.

当用 node_color='blue' 或任何其他颜色绘制图形时,输出工作正常,但是当我使用条件根据 'status' 更改颜色时它只显示一个颜色.

import numpy as np
import matplotlib.pyplot as plt
from random import randint
import networkx as nx

N = 10 #Lattice Size

#Random Coordinate Generator
def random(m, n):
    seen = set()

    x, y = randint(m, n), randint(m, n)

    while True:
        seen.add((x, y))
        yield (x, y)
        x, y = randint(m, n), randint(m, n)
        while (x, y) in seen:
            x, y = randint(m, n), randint(m, n)


#Generates Lattice
G=nx.grid_2d_graph(N,N)
pos = dict( (n, n) for n in G.nodes() )
labels = nx.get_node_attributes(G, 'status') 
G.add_nodes_from(G.nodes,status='1')

#Change Node attribute
num_nodes=N*N
half=int(num_nodes/2)
decaying = [0]*half
a=random(0,N-1)

for i in range(half):
    cor=next(a)
    decaying[i]=cor
for j in range(half):
    a=decaying[j]
    G.add_node(a, status='0')

node_color = []

#Plot nodes
labels = nx.get_node_attributes(G, 'status') 
nx.draw(G,pos=pos,node_color=node_color, labels=labels,node_size=200)

类似这样的方法可行:

import networkx as nx
import matplotlib.pyplot as plt
M = nx.erdos_renyi_graph(10, 2)
color = []
for node in M:
    if node > 1:
        color.append('red')
    else:
        color.append('green')
nx.draw(M, node_color=color)
plt.show()

这里是你例子的应用程序

import numpy as np
import matplotlib.pyplot as plt
from random import randint
import networkx as nx

N = 10 #Lattice Size

#Random Coordinate Generator
def random(m, n):
    seen = set()

    x, y = randint(m, n), randint(m, n)

    while True:
        seen.add((x, y))
        yield (x, y)
        x, y = randint(m, n), randint(m, n)
        while (x, y) in seen:
            x, y = randint(m, n), randint(m, n)


#Generates Lattice
G=nx.grid_2d_graph(N,N)
pos = dict( (n, n) for n in G.nodes() )
labels = nx.get_node_attributes(G, 'status')
G.add_nodes_from(G.nodes,status='1')

#Change Node attribute
num_nodes=N*N
half=int(num_nodes/2)
decaying = [0]*half
a=random(0,N-1)

for i in range(half):
    cor=next(a)
    decaying[i]=cor
for j in range(half):
    a=decaying[j]
    G.add_node(a, status='0')

node_color = []
for status in  list(nx.get_node_attributes(G, 'status').values()):
    if status == '1':
        node_color.append('red')
    else:
        node_color.append('green')
#Plot nodes
labels = nx.get_node_attributes(G, 'status')
nx.draw(G,pos=pos,node_color=node_color, labels=labels,node_size=200)

plt.show()