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

Flask嵌入Bokeh交互式图表遇Bokeh未定义错误求助

解决「Uncaught ReferenceError: Bokeh is not defined」问题

1. 用Bokeh官方工具自动生成资源,避免版本不匹配

别手动写HTML里的Bokeh脚本/样式链接,直接用components函数自动导出所需资源,从根源解决版本不一致问题:

  • 在main.py里修改代码:
    from bokeh.embed import components
    from bokeh.models import Plot, Range1d, LinearAxis, Grid  # 按需导入你的Plot依赖
    
    # 生成Plot实例(必须配置x/y范围)
    plot = Plot(x_range=Range1d(0, 10), y_range=Range1d(0, 10), width=600, height=400)
    # 手动添加轴和网格(Plot类不像figure()自动带这些)
    x_axis = LinearAxis()
    plot.add_layout(x_axis, 'below')
    y_axis = LinearAxis()
    plot.add_layout(y_axis, 'left')
    plot.add_layout(Grid(dimension=0, ticker=x_axis.ticker))
    plot.add_layout(Grid(dimension=1, ticker=y_axis.ticker))
    # 添加你的图形元素(比如GlyphRenderer等)
    
    # 生成嵌入所需的script和div
    script, div = components(plot)
    # 传给模板渲染
    return render_template('index.html', script=script, div=div)
    
  • 在index.html里直接插入生成的内容,不用手动加Bokeh资源:
    {{ script|safe }}
    {{ div|safe }}
    

2. 检查Plot类的初始化完整性

用Plot类而非figure()时,必须手动配置所有核心组件,否则Bokeh无法正常初始化:

  • 必须设置x_range和y_range(用Range1d类)
  • 必须添加至少一组坐标轴和网格
  • 确保已添加可视化元素(比如图形渲染器),空Plot可能导致资源加载异常

3. 手动引入资源时严格匹配版本

如果一定要手动加Bokeh的css/js链接,必须和本地安装的版本完全一致:

  • 先查本地版本:运行pip show bokeh获取版本号(比如2.4.3)
  • 然后在HTML头部添加对应版本的链接:
    <link rel="stylesheet" href="https://cdn.bokeh.org/bokeh/release/bokeh-2.4.3.min.css">
    <script src="https://cdn.bokeh.org/bokeh/release/bokeh-2.4.3.min.js"></script>
    

4. 排查资源加载异常

打开浏览器开发者工具(F12),查看Console面板:

  • 如果有404错误,说明Bokeh资源链接失效或版本不对
  • 如果有其他脚本错误,优先解决这些,可能连锁导致Bokeh无法定义

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 05:10:21