简体   繁体   English

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

[英]How to change colours of nodes and edges of bipartite graph in networkX?

I use this piece of code to draw a bipartite graph using 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)

在此处输入图片说明

Is there a way to randomly change colours of different sets of nodes and edges between them? 有没有一种方法可以随机更改节点边缘之间的不同集合的颜色?

Generate some random numbers: 生成一些随机数:

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

and set the edge color map: 并设置边缘颜色图:

edge_cmap=plt.get_cmap('Blues')

and node color map: 和节点颜色图:

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()

在此处输入图片说明

You could use subgraphs to color connected nodes: 您可以使用子图为连接的节点着色:

    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 )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM