python-3.x - 在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)
我正在处理图形问题,出于调试目的,我需要在每个节点上附加信息以及节点名称。但是,当我附加时,我无法获取名称,如果我附加额外的文本,那么我将无法获取节点名称。
如何将两者都添加到节点而不是边缘?
解决方案
使用此代码,您可以绘制节点 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()
结果
推荐阅读
- php - PHPUnit 测试一个依赖于另一个方法的方法
- javascript - 对单选按钮的值求和并使用 JavaScript 或 jQuery 将其打印到相应的文本框
- time-complexity - 初始化数组和链表的一段代码的大 O 表示法
- regex - 如何从bash中的完整路径中获取文件名和路径
- javascript - 在节点,js(打字稿)中打开文件对话框
- java - Spring Boot 中的配置继承和不同的属性源
- continuous-integration - Gitlab 页面 CI/CD 管道正在通过,但生成的页面不加载资源
- ffmpeg - 生成一秒的黑色视频和相对静音的音频
- python - 如何使用乌龟记录按键?
- javascript - 如何减少使用 && 和 || 的过滤器中的重复 运营商?