问题描述
例如:
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)
我正在处理图形问题,出于调试目的,我需要将每个节点的信息与节点名称一起附加。但是当我附加时,我无法获得名称,如果我附加额外的文本,那么我将无法获得节点名称。
如何在节点上而不是边缘上添加两者?
解决方法
使用此代码,您可以绘制节点 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()
结果