gpt4 book ai didi

python - 我在 NetworkX 图表中看不到标签

转载 作者:太空宇宙 更新时间:2023-11-04 08:07:25 24 4
gpt4 key购买 nike

这是我在 Python 2.7.9 中的代码:

import matplotlib.pyplot as plt
import networkx as nx
socialNetworl = nx.Graph()
socialNetworl.add_nodes_from([1,2,3,4,5,6])
socialNetworl.add_edges_from([(1,2),(1,3),(2,3),(2,5),(2,6)])
nx.draw(socialNetworl, node_size = 800, node_color="cyan")
plt.show()

但是我看不到节点标签。有一行代码我忘记了吗?

最佳答案

只需将 with_labels=True 添加到您的代码中即可。

import matplotlib.pyplot as plt
import networkx as nx
socialNetworl = nx.Graph()
socialNetworl.add_nodes_from([1,2,3,4,5,6])
socialNetworl.add_edges_from([(1,2),(1,3),(2,3),(2,5),(2,6)])
nx.draw(socialNetworl, node_size = 800, node_color="cyan", with_labels = True)
plt.show()

enter image description here

如果你想改变标签,用标签创建一个字典并将labels=theLabelDict传递给nx.draw:

import matplotlib.pyplot as plt
import networkx as nx
socialNetworl = nx.Graph()
socialNetworl.add_nodes_from([1,2,3,4,5,6])
socialNetworl.add_edges_from([(1,2),(1,3),(2,3),(2,5),(2,6)])
labels = {1:'King Arthur', 2:'Lancelot', 3:'shopkeeper', 4:'dead parrot', 5:'Brian', 6:'Sir Robin'}
nx.draw(socialNetworl, node_size = 800, node_color="cyan", labels=labels, with_labels = True)
plt.show()

enter image description here

关于python - 我在 NetworkX 图表中看不到标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28820413/

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