如何在Pyvis框架中固定布局参数实现企业网络默认正确展示?
问题:Pyvis固定企业网络拓扑布局参数,默认展示正确样式
我用Pyvis框架展示企业网络拓扑,当前网络默认随机绘制,必须手动点击布局按钮才能正常显示。想在Python代码里固定布局参数,让网络默认以正确样式展示。
原Python代码:
def openxslx (table_name, name_sheet = 'Sheet1'): x = pd.read_excel(f'{path_track}/{table_name}.xlsx', sheet_name= name_sheet) return x def clear(hostname): hostname_re = re.sub("^\s+|\n|\r|\s+$", '', hostname) hostname_list = hostname_re.split(',') return hostname_list oren = openxslx('XXXXX') nx_graph = net.Network(width='75%', height= '700px', notebook = False, cdn_resources = 'local') for i in range(oren.shape[0]): hostname_a = clear(oren['network_name(tchk_a)'][i]) hostname_b = clear(oren['network_name(tchk_b)'][i]) for hostname in hostname_a: for hostname1 in hostname_b: nx_graph.add_node(hostname, label=f'{hostname}', ) nx_graph.add_node(hostname1, label=f'{hostname1}') nx_graph.add_edge(hostname, hostname1) nx_graph.hrepulsion() nx_graph.toggle_physics(False) nx_graph.show_buttons(filter_=['layout']) nx_graph.show('nx.html')
期望的布局配置参数:
const options = { "layout": { "hierarchical": { "enabled": true, "levelSeparation": -85, "nodeSpacing": 225, "treeSpacing": 310, "direction": "DU", "sortMethod": "directed" } } }
我曾尝试在Network初始化语句中写入这些参数,但运行报错。
解决方法
Pyvis不能直接在Network初始化时传入这类布局参数,需要用set_options()方法将配置以字符串形式传入,同时替换原代码中冲突的物理引擎设置:
- 移除原代码中的
nx_graph.hrepulsion()和nx_graph.toggle_physics(False),因为层级布局的物理规则会和这些方法冲突 - 使用
nx_graph.set_options()将你的布局配置转为字符串传入,注意去掉const options =部分,只保留大括号内的内容
修改后的完整代码:
def openxslx (table_name, name_sheet = 'Sheet1'): x = pd.read_excel(f'{path_track}/{table_name}.xlsx', sheet_name= name_sheet) return x def clear(hostname): hostname_re = re.sub("^\s+|\n|\r|\s+$", '', hostname) hostname_list = hostname_re.split(',') return hostname_list oren = openxslx('XXXXX') nx_graph = net.Network(width='75%', height= '700px', notebook = False, cdn_resources = 'local') for i in range(oren.shape[0]): hostname_a = clear(oren['network_name(tchk_a)'][i]) hostname_b = clear(oren['network_name(tchk_b)'][i]) for hostname in hostname_a: for hostname1 in hostname_b: nx_graph.add_node(hostname, label=f'{hostname}', ) nx_graph.add_node(hostname1, label=f'{hostname1}') nx_graph.add_edge(hostname, hostname1) # 配置层级布局参数 layout_options = """ { "layout": { "hierarchical": { "enabled": true, "levelSeparation": -85, "nodeSpacing": 225, "treeSpacing": 310, "direction": "DU", "sortMethod": "directed" } }, "physics": { "enabled": false } } """ nx_graph.set_options(layout_options) # 如果不需要手动调整布局按钮,可以注释掉下面一行 # nx_graph.show_buttons(filter_=['layout']) nx_graph.show('nx.html')
说明:
- 添加
"physics": {"enabled": false}关闭物理引擎,避免布局自动变动 - 通过
set_options传入完整配置字符串后,生成的HTML会默认应用该布局,无需手动点击布局按钮
内容的提问来源于stack exchange,提问作者Arti
相关产品推荐
相关产品推荐

