gpt4 book ai didi

Python networkx 在使用 draw_networkx_nodes() 时更改节点的颜色

转载 作者:行者123 更新时间:2023-11-28 16:37:14 25 4
gpt4 key购买 nike

目标是获得类似的东西

enter image description here

要定义我使用的图形:

import matplotlib.pyplot as plt
import networkx as nx
graph = {
'1': ['2', '3', '4'],
'2': ['5','11','12','13','14','15'],
'3' : ['6','7','66','77'],
'5': ['6', '8','66','77'],
'4': ['7','66','77'],
'7': ['9', '10']
}

MG = nx.DiGraph()
MG.add_edges_from([(start, stop, {'weigth' : len(graph[start]) })
for start in graph for stop in graph[start]])

绘制它的代码是:

plt.figure(figsize=(8,8))
pos=nx.graphviz_layout(MG,prog="twopi",root='1')
for n in MG.nodes_iter():
nx.draw_networkx_nodes(MG, pos,
nodelist = [n],
node_size = 2000 / float(len(MG[n[0]])+1),
node_color = (len(MG[n[0]])+1),
alpha = 1/float(len(MG[n[0]])+1),
with_labels=True
)
xmax=1.1*max(xx for xx,yy in pos.values())
ymax=1.1*max(yy for xx,yy in pos.values())
plt.xlim(0,xmax)
plt.ylim(0,ymax)
plt.show()

这里有两件事我想知道:

  • 如何根据每个节点的链接数(即 len(MG[0]))获得颜色节点?

  • 我的标签在哪里?

谢谢

最佳答案

这个怎么样?您可以使用 matplotlib 的颜色映射将值映射到节点的颜色。

import matplotlib.pyplot as plt
import networkx as nx
graph = {
'1': ['2', '3', '4'],
'2': ['5','11','12','13','14','15'],
'3' : ['6','7','66','77'],
'5': ['6', '8','66','77'],
'4': ['7','66','77'],
'7': ['9', '10']
}

MG = nx.DiGraph(graph)


plt.figure(figsize=(8,8))
pos=nx.graphviz_layout(MG,prog="twopi",root='1')

nodes = MG.nodes()
degree = MG.degree()
color = [degree[n] for n in nodes]
size = [2000 / (degree[n]+1.0) for n in nodes]

nx.draw(MG, pos, nodelist=nodes, node_color=color, node_size=size,
with_labels=True, cmap=plt.cm.Blues, arrows=False)
plt.show()

enter image description here

关于Python networkx 在使用 draw_networkx_nodes() 时更改节点的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24376200/

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