能否在Python netgraph的边两端各添加一个接口类型标签?
问题
我正在开发一款绘制计算机网络拓扑的应用,选择Python的netgraph库是因为它支持网络交互功能。我尝试修改文档中的代码,希望在边的两端各添加eth0、gig0这类接口类型描述标签,但当前代码生成的是如('eth0','eth1')的单个组合标签,请问能否通过netgraph/networkx实现该需求?
测试代码如下:
import matplotlib.pyplot as plt import networkx as nx from netgraph import InteractiveGraph g = nx.house_x_graph() edge_color = dict() for ii, edge in enumerate(g.edges): edge_color[edge] = 'tab:gray' if ii%2 else 'tab:orange' node_color = dict() for node in g.nodes: node_color[node] = 'tab:red' if node%2 else 'tab:blue' edge_labels = {(1, 2): ('eth0','eth1'), (2, 3): ('gig0','gig1') } plot_instance = InteractiveGraph( g, node_size=5, node_color=node_color, node_labels=True, node_label_offset=0.1, node_label_fontdict=dict(size=20), edge_color=edge_color, edge_width=1,edge_labels=edge_labels, edge_label_position=0.2) plt.show()
当前效果:边的中间位置显示元组格式的组合文本,无法在边的两端分别展示独立的接口标签。
解决方案
可以通过拆分接口标签并多次调用draw_edge_labels方法实现需求,具体步骤如下:
- 将原有的组合标签拆分为两个字典,分别对应边的起点端和终点端接口;
- 初始化
InteractiveGraph时不传入edge_labels参数; - 调用实例的
draw_edge_labels方法两次,分别设置靠近起点和终点的标签位置与内容。
修改后的代码:
import matplotlib.pyplot as plt import networkx as nx from netgraph import InteractiveGraph g = nx.house_x_graph() edge_color = dict() for ii, edge in enumerate(g.edges): edge_color[edge] = 'tab:gray' if ii%2 else 'tab:orange' node_color = dict() for node in g.nodes: node_color[node] = 'tab:red' if node%2 else 'tab:blue' # 拆分接口标签为起点端和终点端两个字典 edge_labels_source = {(1, 2): 'eth0', (2, 3): 'gig0'} edge_labels_target = {(1, 2): 'eth1', (2, 3): 'gig1'} plot_instance = InteractiveGraph( g, node_size=5, node_color=node_color, node_labels=True, node_label_offset=0.1, node_label_fontdict=dict(size=20), edge_color=edge_color, edge_width=1 ) # 绘制靠近起点的接口标签,位置设为贴近节点(0.05表示距离起点5%的边长度位置) plot_instance.draw_edge_labels(edge_labels_source, edge_label_position=0.05, edge_label_fontdict=dict(size=12)) # 绘制靠近终点的接口标签,位置设为贴近另一端节点(0.95表示距离起点95%的边长度位置) plot_instance.draw_edge_labels(edge_labels_target, edge_label_position=0.95, edge_label_fontdict=dict(size=12)) plt.show()
说明:
edge_label_position参数的取值范围是0到1,0对应边的起点,1对应边的终点;- 可以根据需要调整
edge_label_fontdict中的字体大小等样式,保证标签与拓扑图的视觉协调性; - 若处理无向边,需确保字典中的边键与图中存储的边顺序一致(networkx无向图的边默认按节点升序存储)。
内容的提问来源于stack exchange,提问作者Rayugo
相关产品推荐
相关产品推荐

