python和networkx:如何更改节点的颜色

时间:2013-12-11 15:36:49

标签: python graph networkx

我正在使用python和“networkx”随机分配边缘到点头。点头分为两类,每个类别的节点数相同。代码正在运行,但我有一个问题:如何更改节点的颜色?现在,两个类别的节点都具有sam颜色。

import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
N = int(raw_input("Enter the number of each race to be used: "))

gamma = float(raw_input("Enter the probability of same-race ties: "))

delta = float(raw_input("Enter the probability of cross-race ties: "))
connectr11 = np.zeros((N,N),dtype=np.int32)

for i in range(0,N):
        dval = np.diag((np.random.random_sample(size=(N-i))<gamma).astype(np.int32),i)
        connectr11 += dval
        if (i>0):
                connectr11 += dval.T
##print connectr11

connectr22 = np.zeros((N,N),dtype=np.int32)

for i in range(0,N):
        dval = np.diag((np.random.random_sample(size=(N-i))<gamma).astype(np.int32),i)
        connectr22 += dval
        if (i>0):
                connectr22 += dval.T

##print connectr22

connectr12 = np.zeros((N,N),dtype=np.int32)

for i in range(0,N):
        dval = np.diag((np.random.random_sample(size=(N-i))<delta).astype(np.int32),i)
        connectr12 += dval
        if (i>0):
                connectr12 += dval.T

##print connectr12


connectr21 = np.zeros((N,N),dtype=np.int32)

for i in range(0,N):
        dval = np.diag((np.random.random_sample(size=(N-i))<delta).astype(np.int32),i)
        connectr12 += dval
        if (i>0):
                connectr12 += dval.T
##print connectr21

concr1x=np.concatenate((connectr11, connectr12), axis=0)
concrx2=np.concatenate((connectr21, connectr22), axis=0)
concr12=np.concatenate((concr1x, concrx2), axis=1)
##print concr12


print concr12


A=np.matrix(concr12)
G=nx.from_numpy_matrix(A)


for i in range(0,N):
    if i < N: 
        G.node[i] = 1
        node_color='b'
    else:
        G.node[i] = 0
        node_color='r'



nx.draw_circular(G, node_color=node_color)
plt.show()

1 个答案:

答案 0 :(得分:3)

您希望node_color成为列表。在第2行到最后一行中,分配node_color = node_color会使所有节点成为分配给node_color的最后一个值。你想要的是一个与你拥有的节点数相等长度的列表。

    node_colors =[]
    node_colors.append('r')

尝试:

    for i in range(0,N):
        if i < N:
           node_colors.append('b')
        else: 
           node_colors.append('r')
    nx.draw_circular(G, node_color = node_colors)
    plt.show()