微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在 networkx 中添加带有节点名称的描述

如何解决在 networkx 中添加带有节点名称的描述

我正在尝试添加带有节点名称的描述/文本。

例如:

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

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

Default Labels

如果我使用自定义标签

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

我得到这张图:

Custom Label

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

如何在节点上而不是边缘上添加两者?

解决方法

使用此代码,您可以绘制节点 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()

结果

Figure with Labels and Node Id

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。