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

如何通过JavaScript修改Bokeh图表figure的image_url背景图像

Bokeh动态修改图表背景图解决方案

错误原因

  • 调用p.image_url()会返回独立的GlyphRenderer实例,图片URL属性存储在该实例的glyph属性下,直接修改figure对象的url/image_url属性无效
  • 未给背景图设置宽高和正确锚点,可能导致背景图超出绘图范围无法正常显示
  • 原代码中CustomJS的args参数里传入的ecg_source未提前定义,属于拼写错误

修正后的测试代码(按钮触发背景切换)

from bokeh.models import AjaxDataSource, Button, CustomJS
from bokeh.plotting import figure

img_yellow = "http://localhost:8000/static/images/semaforo_yellow.png"
img_green = "http://localhost:8000/static/images/semaforo_verde.png"
img_red = "http://localhost:8000/static/images/semaforo_rosso.png"

p = figure(x_range=(0, 1), y_range=(0, 1))
# 存储背景图渲染器,设置宽高和锚点刚好铺满整个绘图区域
bg_renderer = p.image_url(
    url=[img_yellow], 
    x=0, y=1, 
    w=1, h=1, 
    anchor="top_left"
)

# 定时拉取接口的数据源
source = AjaxDataSource(
    data_url="http://localhost:8000/rt/semaforo",
    polling_interval=50000  # 单位为毫秒,50000即每50秒拉取一次接口
)
p.circle('x', 'y', source=source)

print_button = Button(label="Print")
print_button.js_on_click(CustomJS(
    args=dict(bg_renderer=bg_renderer), 
    code="""
        // 修改背景渲染器的图片URL
        bg_renderer.glyph.url = ["http://localhost:8000/static/images/semaforo_rosso.png"];
        // 触发渲染更新
        bg_renderer.change.emit();
    """
))

自动根据接口返回切换背景实现

如果要实现定时拉取接口后自动根据响应结果切换背景,无需按钮触发,直接给AjaxDataSource添加数据更新回调即可,示例如下:

# 接口返回数据中需包含semaforo_status字段,取值为red/green/yellow
source.js_on_change('data', CustomJS(
    args=dict(bg_renderer=bg_renderer),
    code="""
        const status = cb_obj.data.semaforo_status[0];
        let targetUrl;
        if (status === 'red') {
            targetUrl = "http://localhost:8000/static/images/semaforo_rosso.png";
        } else if (status === 'green') {
            targetUrl = "http://localhost:8000/static/images/semaforo_verde.png";
        } else {
            targetUrl = "http://localhost:8000/static/images/semaforo_yellow.png";
        }
        bg_renderer.glyph.url = [targetUrl];
        bg_renderer.change.emit();
    """
))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 01:00:05