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

Bokeh Server双Y轴绘图正常,添加第三Y轴后页面空白求排查

解决Bokeh Server多Y轴实时绘图页面空白问题

我帮你找出了代码里导致页面空白的两个关键问题,修复后就能正常运行多Y轴实时绘图了:

1. 错误覆盖了额外Y轴范围配置

你在添加第三个Y轴时,直接用fig.extra_y_ranges = {"foo2": Range1d(start=0, end=25)}重新赋值,这会把之前定义的foo1范围完全覆盖掉。Bokeh需要保留所有额外Y轴的范围配置,正确的做法是用update方法来添加新的范围,而不是直接替换整个字典。

2. 引用了未定义的变量df

在update_data函数的else分支里,你用了len(df['a']),但代码里从来没有定义过df变量,这会导致运行时错误,进而让页面无法正常渲染。应该改为从source.data中获取数据长度。

修正后的完整代码

from bokeh.io import curdoc
from bokeh.models import ColumnDataSource
from bokeh.plotting import figure
from bokeh.models import LinearAxis, Range1d
import numpy as np

def plotcharts(source,x,a,b,c):
    fig=figure(y_range=(0, 500))
    fig.circle(source=source, x=x,y=a,size=12,color='red')
    # 初始化额外Y轴范围字典
    fig.extra_y_ranges = {"foo1": Range1d(start=0, end=50)}
    fig.circle(source=source,x=x, y=b, size=12, color="blue", y_range_name="foo1")
    fig.add_layout(LinearAxis(y_range_name="foo1"), 'left')
    # 使用update添加第三个Y轴范围,而非替换整个字典
    fig.extra_y_ranges.update({"foo2": Range1d(start=0, end=25)})
    fig.circle(source=source, x=x, y=c, color="magenta", y_range_name="foo2")
    fig.add_layout(LinearAxis(y_range_name="foo2"), 'right')
    return fig

count=(-1)
dct=dict(x=[],a=[],b=[],c=[])
source=ColumnDataSource(dct)
fig=plotcharts(source,'x','a','b','c')

def update_data():
    global count
    count=count+1
    y1 = np.random.randint(low=0, high=500)
    y2 = np.random.randint(low=0, high=50)
    y3 = np.random.randint(low=0, high=25)
    if count%3==0:
        new_data = {
            'x': [count/3],
            'a': [y1],
            'b': [y2],
            'c': [y3]
        }
        source.stream(new_data,rollover=20)
    else:
        # 从source.data获取数据长度,替换未定义的df
        l = len(source.data['a'])
        if l == 0:
            # 避免初始无数据时的索引错误
            return
        new_data = {
            'a': [(l - 1,y1)],
            'b': [(l - 1, y2)],
            'c': [(l - 1, y3)]
        }
        source.patch(new_data)

curdoc().add_root(fig)
curdoc().add_periodic_callback(update_data,1000)

额外优化说明

我还添加了if l == 0:的判断,避免第一次运行update_data且还没通过stream添加数据时,出现索引越界的错误。现在三个Y轴会分别对应红色(主Y轴)、蓝色(左额外Y轴)、洋红色(右额外Y轴)的点,实时更新功能也能正常工作了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:15:26