You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在pyvis可视化NetworkX图时显示交互按钮并为生成的HTML加标题

交互按钮不显示解决方案

按钮不显示的核心原因是初始化Network对象时设置了notebook = True参数,该参数专为Jupyter Notebook内嵌可视化设计,会屏蔽独立HTML文件的控件渲染逻辑。

  • 解决步骤1:将Network实例化代码中的notebook = True删除,或修改为notebook = False
  • 解决步骤2:如果修改后仍未显示,可先去掉show_buttons的filter_参数测试基础功能是否正常,即改为N.show_buttons(),确认显示后再按需配置过滤规则
  • 可选排查:如果上述操作无效,升级pyvis到最新版本:pip install --upgrade pyvis

为HTML页面添加标题解决方案

pyvis未提供直接设置页面标题的接口,可通过修改生成后的HTML文件内容实现,逻辑为读取生成的HTML代码,在<head>标签内插入<title>标签即可。

修改后完整代码

def visualize(identity_id,html_name):
    # 根据传入的identity_id提取子图
    classx = [n for n in G.nodes() if G.nodes[n]['modularity'] == 
              G.nodes[identity_id]['modularity']]
    SG = G.subgraph(classx)

    # 移除notebook=True参数适配独立HTML生成
    N = Network(height='100%', width='100%', bgcolor='#ffffff', 
                font_color='black', directed=False)

    # 配置HTML文件的物理引擎参数
    N.barnes_hut(spring_strength=0.006)

    # 配置节点颜色和形状
    for n in SG:
        if (SG.nodes[n]['category']=='cust') and (SG.nodes[n]['status']=='ACTIVE'):
            color = 'green'
            shape = 'square'
        if (SG.nodes[n]['category']=='cust') and (SG.nodes[n]['status']=='CLOSED'):
            color = 'red'
            shape = 'square'   
        elif SG.nodes[n]['category']=='app':
            color = 'blue'
            shape = 'triangle'
        N.add_node(n, label=n, color=color,shape = shape)

    # 配置边的颜色和宽度
    for e in SG.edges:
        if e in SG.edges:
            color = 'black'
            width = 2
        N.add_edge(e[0],e[1],color=color, width=width)

    N.show_buttons(filter_=True)
    # 生成初始HTML文件
    html_path = f'subgraph_{html_name}.html'
    N.write_html(html_path)
    
    # 插入自定义页面标题
    with open(html_path, 'r', encoding='utf-8') as f:
        html_content = f.read()
    # 可按需修改标题内容规则
    page_title = f"关系子图可视化-{html_name}"
    modified_content = html_content.replace('<head>', f'<head>\n<title>{page_title}</title>')
    with open(html_path, 'w', encoding='utf-8') as f:
        f.write(modified_content)
    
    # 如果需要生成后自动打开页面,可放开以下代码
    # import webbrowser
    # webbrowser.open_new_tab(html_path)

内容的提问来源于stack exchange,提问作者AAA

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 06:39:03