gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 04:07:24 29 4
gpt4 key购买 nike

我使用这段代码使用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

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

最佳答案

生成一些随机数:

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

关于python - 如何更改networkX中二分图的节点和边的颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35392342/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com