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

如何在Bokeh中正确填充阶梯图下方区域?

Bokeh阶梯图下方填充区域异常的解决方法

问题原因

直接用varea函数配合阶梯图的原始数据会导致填充异常——varea是基于连续折线连接相邻数据点,而阶梯图的绘制逻辑是水平段+垂直段的组合,原始数据的点之间没有体现阶梯的水平延伸,所以填充时会出现斜线连接的错误。

解决方案

构造符合阶梯图逻辑的填充数据:将每个数据点(最后一个除外)复制一份,绑定到下一个时间点,模拟阶梯的水平段,让varea能沿着阶梯形状填充。

修改后的完整代码

import numpy as np
from bokeh.plotting import figure, show
from bokeh.models import ColumnDataSource, NumeralTickFormatter, DatetimeTickFormatter, HoverTool
from math import pi
from datetime import datetime

datetimes = [datetime(2022, 9, 30, 3, 8, 8, 239000),
             datetime(2022, 10, 1, 3, 8, 8, 239000),
             datetime(2022, 10, 20, 3, 8, 8, 239000)]
             
values = np.random.random(3)

# 构造阶梯填充专用数据
filled_dates = []
filled_values = []
for i in range(len(datetimes)):
    filled_dates.append(datetimes[i])
    filled_values.append(values[i])
    if i < len(datetimes) - 1:
        filled_dates.append(datetimes[i+1])
        filled_values.append(values[i])

fig = figure(x_axis_type="datetime", toolbar_location=None, y_range=(0, 1), y_axis_location='right', height=250, width=635)
fig.yaxis[0].formatter = NumeralTickFormatter(format='0%')
fig.xaxis.major_label_orientation = pi/4
fig.xaxis.formatter=DatetimeTickFormatter(
        hours=["%d %B %Y"],
        days=["%d %B %Y"],
        months=["%d %B %Y"],
        years=["%d %B %Y"],
    )
hover = HoverTool(tooltips=[('values', '@values{0.0%}')])
fig.toolbar.active_drag = None

# 原始阶梯图数据源
plot_source = ColumnDataSource(data=dict(date=datetimes, values=values))
line_plot = fig.step("date", "values", source=plot_source, line_width=1, color="#285e61")
fig.add_tools(hover)

# 使用构造好的填充数据绘制填充区域
fill_source = ColumnDataSource(data=dict(date=filled_dates, values=filled_values))
fig.varea(source=fill_source, x="date", y1=0, y2="values", alpha=0.2, fill_color='#38b2ac')

show(fig)

效果说明

修改后,填充区域会严格跟随阶梯图的水平段和垂直段,不再出现斜线填充的异常,完美匹配阶梯图的形状。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 23:55:26