首页 > 解决方案 > 在networkx中添加带有节点名称的描述

问题描述

我正在尝试使用节点名称添加描述/文本。

例如 :

import networkx as nx
G = nx.Graph()
G.add_edge(1,2)
G.add_edge(2,3)
nx.draw(G,with_labels=True)

上面的代码会给我这个以节点名称作为标签的图表。

默认标签

如果我使用自定义标签:

labels = {}
labels[1] = 'First Node'
labels[2] = 'Second Node'
labels[3] = 'Third Node'
nx.draw(G,labels=labels,with_labels=True)

我得到这张图: 自定义标签

我正在处理图形问题,出于调试目的,我需要在每个节点上附加信息以及节点名称。但是,当我附加时,我无法获取名称,如果我附加额外的文本,那么我将无法获取节点名称。

如何将两者都添加到节点而不是边缘?

标签: python-3.xlabelnetworkx

解决方案


使用此代码,您可以绘制节点 ID 和其他信息:

import networkx as nx
import matplotlib.pylab as pl

G = nx.Graph()
G.add_edge(1, 2)
G.add_edge(2, 3)

# get positions
pos = nx.spring_layout(G)

nx.draw(G, pos, with_labels=True)

# shift position a little bit
shift = [0.1, 0]
shifted_pos ={node: node_pos + shift for node, node_pos in pos.items()}

# Just some text to print in addition to node ids
labels = {}
labels[1] = 'First Node'
labels[2] = 'Second Node'
labels[3] = 'Third Node'
nx.draw_networkx_labels(G, shifted_pos, labels=labels, horizontalalignment="left")

# adjust frame to avoid cutting text, may need to adjust the value
axis = pl.gca()
axis.set_xlim([1.5*x for x in axis.get_xlim()])
axis.set_ylim([1.5*y for y in axis.get_ylim()])
# turn off frame
pl.axis("off")

pl.show()

结果

带有标签和节点 ID 的图


推荐阅读