如何在networkX中更改二分图的节点和边缘的颜色?

时间:2016-02-14 13:27:25

标签: python graph networkx

我使用这段代码使用 networkX 绘制二分图:

import networkx as nx

G = bipartite.from_biadjacency_matrix(a_matrix, create_using=None, edge_attribute='weight')
X, Y = bipartite.sets(G)
pos = dict()
pos.update((n, (0, i*10)) for i, n in enumerate(X))
pos.update((n, (0.5, i*10)) for i, n in enumerate(Y))
nx.draw(G, pos=pos)

enter image description here

有没有办法随机更改它们之间不同节点的颜色?

2 个答案:

答案 0 :(得分:2)

生成一些随机数:

edge_color=np.random.random(num_edges)
node_color=np.random.random(num_nodes)

并设置边缘颜色贴图:

edge_cmap=plt.get_cmap('Blues')

和节点颜色映射:

cmap=plt.get_cmap('Reds')
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
from networkx.algorithms import bipartite
import scipy.sparse as sparse

a_matrix = sparse.rand(10, 10, format='coo', density=0.8)

G = bipartite.from_biadjacency_matrix(a_matrix, create_using=None, 
                                         edge_attribute='weight')
X, Y = bipartite.sets(G)
pos = dict()
pos.update((n, (0, i*10)) for i, n in enumerate(X))
pos.update((n, (0.5, i*10)) for i, n in enumerate(Y))
num_edges = G.number_of_edges()
num_nodes = G.number_of_nodes()
nx.draw(G, pos=pos, with_labels=True,
        edge_color=np.random.random(num_edges), 
        edge_cmap=plt.get_cmap('Blues'), 
        node_color=np.random.random(num_nodes),
        cmap=plt.get_cmap('Reds'))
plt.show()

enter image description here

答案 1 :(得分:0)

您可以使用子图为连接的节点着色:

    C = nx.connected_component_subgraphs(G)
    for g in C:
         node_colors = [random.random()] * nx.number_of_nodes(g)
         nx.draw(g, pos, node_size=40, node_color=node_colors, vmin=0.0, vmax=1.0, with_labels=False )