如何使用 networkx 在图形中显示节点名称?

How to show node name in graphs using networkx?

我有密码

import networkx as nx
import matplotlib.pyplot as plt

G = nx.DiGraph()

G.add_nodes_from([1, 2, 3, 4])
G.add_edges_from([(1, 2), (2, 1), (2, 3)])

nx.draw(G)
plt.savefig("graph.png")
plt.show()

并绘制了下图:

但是,我需要显示标签。 如何在图表的节点内显示数值和单词(一、二、三和四)?

你只需要用nx.Draw():

调用with_labels=True参数
import networkx as nx
import matplotlib.pyplot as plt

G = nx.DiGraph()

G.add_nodes_from([1, 2, 3, 4])
G.add_edges_from([(1, 2), (2, 1), (2, 3)])

nx.draw(G,with_labels=True)
plt.savefig("graph.png")
plt.show()

您还可以调用font_sizefont_color

在此处查看文档: https://networkx.github.io/documentation/latest/reference/drawing.html