Bokeh绘制4小时周期OHLC蜡烛图时如何去除周末缺失日期的时间轴间隙
Bokeh绘制金融K线消除周末间隙解决方案
问题原因
你没有正确理解对应方案的逻辑,问题核心如下:
- 你仍然使用了datetime类型作为x轴的输入值,Bokeh的datetime轴会严格按照实际时间差计算元素的坐标位置,周末没有交易数据的时段自然会产生空白间隙。
major_label_overrides配置仅能修改轴标签的显示文本,无法改变元素本身的坐标排布,所以仅添加这行配置不会解决间隙问题。- 补充小错误:你原有代码中的时间格式化字符串有误,
%S是秒的占位符,要显示分钟应该用%M。
正确修改方案
核心思路是用连续整数作为x坐标,从根源上消除时间间隔带来的坐标差,再通过标签映射把x轴显示内容替换为对应时间:
- 移除x轴的datetime类型配置,改用默认的线性轴
- 用连续整数作为所有绘图元素的x坐标,每个整数对应一根K线,保证坐标间距均匀
- 调整蜡烛宽度为适配线性轴的小数值,不再使用时间差计算宽度
- 修正时间格式化字符串,按需调整x轴标签密度避免重叠
修改后完整代码
import pandas as pd from bokeh.plotting import figure, show, gridplot # 原有数据加载、重采样逻辑保持不变 subdata = pd.read_csv( 'data/M5/EURUSD.csv', header = None, skiprows = 0, sep = '\t', names = [ 'date', 'open', 'high', 'low', 'close', 'volume' ], ) subdata['date'] = pd.to_datetime(subdata['date']) subdata.set_index(['date'], inplace = True) subdata = subdata.resample('4H').agg({ 'open': 'first', 'high': 'max', 'low': 'min', 'close': 'last', 'volume': 'sum' }).dropna(axis=0) # ---------------- 绘图逻辑修改部分 ---------------- # 移除x_axis_type='datetime'参数,使用默认线性轴 fig1 = figure(height=400, width=900) # 生成连续整数作为x坐标 x_coords = range(len(subdata)) # 修正时间格式化字符串,将整数坐标映射为对应时间文本 fig1.xaxis.major_label_overrides = { i: date.strftime('%Y-%m-%d %H:%M') for i, date in enumerate(subdata.index) } # 可选:倾斜x轴标签避免重叠 fig1.xaxis.major_label_orientation = 3.14/4 # 蜡烛宽度适配线性轴,不需要按时间差计算 candle_width = 0.6 inc = subdata['close'] > subdata['open'] dec = subdata['open'] > subdata['close'] # 所有绘图方法的x参数替换为连续整数坐标 fig1.segment(x_coords, subdata['high'], x_coords, subdata['low'], color='black') fig1.vbar([x_coords[i] for i in range(len(x_coords)) if inc.iloc[i]], candle_width, subdata['open'][inc], subdata.close[inc], fill_color='#D5E1DD', line_color='black') fig1.vbar([x_coords[i] for i in range(len(x_coords)) if dec.iloc[i]], candle_width, subdata['open'][dec], subdata['close'][dec], fill_color='#F2583E', line_color='black') show(gridplot([[fig1]]))
如果觉得x轴标签过密,可以调整major_label_overrides的映射规则,比如每5个索引才保留一个映射,其余留空即可减少标签数量。
内容的提问来源于stack exchange,提问作者Inu Bayu Aji
相关产品推荐
相关产品推荐

