[英]Networkx, changing node colors
I want to change the color of the node, based on the attribute values.我想根据属性值更改节点的颜色。 Specifically in this case, when the attribute 'status' is 1, I want the color to be something and when it's 0, some other color.
具体来说,在这种情况下,当属性“status”为 1 时,我希望颜色为某种颜色,而当它为 0 时,则为其他颜色。 One restriction is that I want the nodes to be printed in a lattice format, where I use 2d_grid_graph.
一个限制是我希望节点以点阵格式打印,我在这里使用 2d_grid_graph。
When graphing this with node_color='blue' or any other color, the output works correctly, but when I use conditionals to change the color according to 'status' it only shows one color.当使用 node_color='blue' 或任何其他颜色对其进行绘图时,output 可以正常工作,但是当我使用条件语句根据“状态”更改颜色时,它只显示一种颜色。
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)
Something like this could works:这样的事情可能有效:
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()
Here the application with your example这里有你的例子的应用程序
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.