这是我在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()
但我看不到节点标签。我忘记了一行代码吗?
答案 0 :(得分:3)
您可以使用nx.draw_networkx_labels
单独绘制节点标签(并控制许多其他标签选项)。例如,在添加节点和边之后,您可以编写:
pos=nx.spring_layout(socialNetworl)
nx.draw(socialNetworl, pos=pos, node_size = 800, node_color="cyan")
nx.draw_networkx_labels(socialNetworl, pos=pos);
plt.show()
哪个绘制:
答案 1 :(得分:2)
只需在代码中添加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()
如果您想更改标签,请使用标签创建一个字典,并将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()