且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用默认为节点名称的节点标签绘制networkx图

更新时间:2023-11-21 15:08:46

tl/dr:只需将with_labels=True添加到nx.draw调用中即可.

tl/dr: just add with_labels=True to the nx.draw call.

您正在查看的页面有点复杂,因为它显示了如何设置很多不同的东西作为标签,如何为不同的节点赋予不同的颜色,以及如何提供仔细控制节点的位置.因此,发生了很多事情.

The page you were looking at is somewhat complex because it shows how to set lots of different things as the labels, how to give different nodes different colors, and how to provide carefully control node positions. So there's a lot going on.

但是,您似乎只希望每个节点使用其自己的名称,并且对默认颜色和默认位置感到满意.所以

However, it appears you just want each node to use its own name, and you're happy with the default color and default position. So

import networkx as nx
import pylab as plt

G=nx.Graph()
# Add nodes and edges
G.add_edge("Node1", "Node2")
nx.draw(G, with_labels = True)
plt.savefig('labels.png')

如果您想做一些事情以使节点标签不同,则可以发送dict作为参数.例如,

If you wanted to do something so that the node labels were different you could send a dict as an argument. So for example,

labeldict = {}
labeldict["Node1"] = "shopkeeper"
labeldict["Node2"] = "angry man with parrot"

nx.draw(G, labels=labeldict, with_labels = True)