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

Bokeh 3自定义分类轴标签:显示间隔标签或合理标记时长分箱

Bokeh 3.x 直方图标签间隔显示解决方案

一、分类轴直接过滤标签(兼容Bokeh 3.x)

针对分类轴的标签重叠问题,Bokeh 3.x可通过FuncTickFormatter实现间隔显示标签,核心是通过刻度索引判断是否渲染标签。

实现代码

from bokeh.plotting import figure, show
from bokeh.models import FuncTickFormatter

# 模拟分箱数据
bin_labels = ["0:00-0:30", "0:30-1:00", "1:00-1:30", "1:30-2:00", "2:00-2:30", "2:30-3:00"]
event_counts = [120, 95, 70, 55, 30, 15]

# 创建绘图对象
p = figure(x_range=bin_labels, title="站点访问时长分布", 
           x_axis_label="访问时长", y_axis_label="事件数量")
p.vbar(x=bin_labels, top=event_counts, width=0.8)

# 设置x轴标签:每隔一个显示(索引为偶数的标签保留)
p.xaxis.formatter = FuncTickFormatter(code="""
    return (tick.index % 2 === 0) ? tick.value : "";
""")

# 可选:调整标签角度避免剩余标签重叠
p.xaxis.major_label_orientation = 0.75

show(p)

若需指定特定索引的标签显示,可修改JS逻辑:

// 仅显示索引0、2、4的标签
const keepIndices = [0, 2, 4];
return keepIndices.includes(tick.index) ? tick.value : "";

二、非分类数值轴方案(推荐用于时段/月份分箱)

对于时长、时段、月份这类有序分箱,将分类标签转换为数值型数据,使用数值轴替代分类轴,可从根源解决标签拥挤问题,同时更贴合数据的连续性特征。

实现代码

from bokeh.plotting import figure, show
from bokeh.models import FixedTicker, FuncTickFormatter

# 将分箱转换为数值起始值(秒)与对应标签
bin_starts = [0, 30, 60, 90, 120, 150]
bin_labels = ["0:00-0:30", "0:30-1:00", "1:00-1:30", "1:30-2:00", "2:00-2:30", "2:30-3:00"]
event_counts = [120, 95, 70, 55, 30, 15]
bin_width = 30  # 分箱间隔(秒)

# 创建绘图对象
p = figure(title="站点访问时长分布", x_axis_label="访问时长", 
           y_axis_label="事件数量", x_range=(0, bin_starts[-1] + bin_width))

# 绘制数值型直方图(x为分箱中点)
p.vbar(x=[s + bin_width/2 for s in bin_starts], top=event_counts, width=bin_width*0.8)

# 设置固定刻度位置(对应分箱中点)
p.xaxis.ticker = FixedTicker(ticks=[s + bin_width/2 for s in bin_starts])

# 将数值转换为分箱标签,每隔一个显示
p.xaxis.formatter = FuncTickFormatter(code="""
    const labels = ["0:00-0:30", "0:30-1:00", "1:00-1:30", "1:30-2:00", "2:00-2:30", "2:30-3:00"];
    const index = Math.floor(tick.value / 30);
    return (index % 2 === 0) ? labels[index] : "";
""")

p.xaxis.major_label_orientation = 0.75

show(p)

该方案优势:

  • 利用数值轴的刻度控制能力,避免分类轴的标签拥挤;
  • 适配月份、时段等有序分箱,可通过时间戳转换实现类似逻辑,扩展性更强。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 08:31:18