我在 NetworkX 图中看不到标签

GSa*_*ngs 2 python networkx

这是我在 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()
Run Code Online (Sandbox Code Playgroud)

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

Joe*_*oel 5

只需添加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()
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

如果要更改标签,创建标签和合格的字典labels=theLabelDictnx.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()
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明