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

Pyvis图表filter_menu选项在Streamlit中无法渲染的技术求助

Pyvis图表在Streamlit中空白(带filter_menu=True)的解决方法

问题说明

用Pyvis生成带filter_menu=True选项的HTML图表,直接打开完全正常,但放到Streamlit里渲染就只显示空白背景。生成图表的原代码:

node_degree = dict(G.degree())

net = Network(notebook = True ,
              width = '100%',
              height = '1000px',
              bgcolor  = '#222222',
              font_color = 'white',
              filter_menu=True)

nx.set_node_attributes(G, node_degree , 'size')
nx.set_node_attributes(G, event_level1_dict,'group')

net.from_nx(G)
net.show_buttons()
net.show('witcher2.html')

可行解决方案

方案1:调整Pyvis初始化 + 用Streamlit原生组件渲染

这是最常用的修复方式,核心是关闭Pyvis的笔记本模式,适配Streamlit的沙箱环境:

  • 把notebook=True改成notebook=False(这个参数是给Jupyter用的,在Streamlit里会干扰JS加载)
  • 用write_html()代替show()生成HTML文件,避免自动添加Jupyter相关的JS
  • 用Streamlit的components.html()加载,设置足够的高度和滚动属性

调整后的完整代码:

# 生成Pyvis图表的代码
import networkx as nx
from pyvis.network import Network

node_degree = dict(G.degree())
net = Network(
    notebook=False,  # 关键修改:关闭notebook模式
    width='100%',
    height='1000px',
    bgcolor='#222222',
    font_color='white',
    filter_menu=True
)

nx.set_node_attributes(G, node_degree, 'size')
nx.set_node_attributes(G, event_level1_dict, 'group')

net.from_nx(G)
net.show_buttons()
net.write_html('witcher2.html')  # 替换show()为write_html()

# Streamlit渲染代码
import streamlit as st
from streamlit.components.v1 import html

with open('witcher2.html', 'r', encoding='utf-8') as f:
    html_content = f.read()

# 设置height要比图表高度稍大,确保filter菜单能完整显示
html(html_content, height=1100, scrolling=True)

方案2:修复HTML中的JS依赖路径

如果方案1无效,可能是Pyvis生成的HTML里部分JS用了相对路径,在Streamlit沙箱里加载失败:

  1. 打开生成的witcher2.html文件
  2. 查找所有<script>标签,把相对路径的JS替换成CDN链接(比如jQuery用https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js)
  3. 保存后再用Streamlit加载修改后的HTML

方案3:用第三方适配组件

直接用专门为Streamlit做的Pyvis组件,自动处理兼容性问题:

  1. 先安装组件:
pip install pyvis-streamlit
  1. 直接传入Pyvis的Network对象渲染:
import streamlit as st
from pyvis_streamlit import pyvis_streamlit

# 这里net是你创建好的Pyvis Network对象(已经完成from_nx、show_buttons等操作)
pyvis_streamlit(net, height=1000)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 17:50:43