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

如何按activity分类列为Bokeh时间区间图的区间块着色

实现方法

你可以通过Bokeh内置的因子颜色映射功能,或者手动给DataFrame新增颜色列的方式实现按activity类别着色,以下是两种可行方案:

方案1:使用factor_cmap自动映射(无需修改原DataFrame)

  1. 首先导入颜色映射依赖:
from bokeh.transform import factor_cmap
from bokeh.palettes import Category10 # 可根据需要替换为其他调色板
  1. 调整完整代码如下:
import pandas as pd
from bokeh.models import ColumnDataSource
from bokeh.plotting import figure, output_file, show
from bokeh.transform import factor_cmap
from bokeh.palettes import Category10

# 此处省略你的df定义逻辑
cds=ColumnDataSource(df)
p=figure(x_axis_type='datetime', height=150, width=500, sizing_mode='scale_width', title='Prediction Graph')
p.yaxis.minor_tick_line_color=None
# 可选:隐藏无实际含义的y轴刻度标签
p.yaxis.ticker = []

# 获取所有activity的唯一值作为分类因子
activity_types = df['activity'].unique().tolist()
# 给quad添加颜色映射,同时配置legend_field显示图例
p.quad(
    left='start', 
    right='end', 
    top=1, 
    bottom=0, 
    source=cds,
    # 颜色映射参数依次为:对应字段名、调色板、分类列表
    color=factor_cmap('activity', palette=Category10[len(activity_types)], factors=activity_types),
    legend_field='activity'
)

# 可选:调整图例位置
p.legend.location = 'top_right'

output_file('PredictionGraph.html')
show(p)

方案2:手动指定每个activity的对应颜色(自定义程度更高)

如果你需要给指定activity设置固定颜色,比如「工作」固定为蓝色、「休息」固定为绿色,可以直接给原DataFrame新增颜色列:

# 自定义颜色映射规则,根据你的实际activity值调整键值对即可
color_map = {
    "工作": "#2196F3",
    "休息": "#4CAF50",
    "运动": "#FF9800",
    "睡眠": "#9C27B0"
}
# 给df新增color列
df['color'] = df['activity'].map(color_map)

# 后续绘图代码直接调用color列即可
cds=ColumnDataSource(df)
p=figure(x_axis_type='datetime', height=150, width=500, sizing_mode='scale_width', title='Prediction Graph')
p.yaxis.minor_tick_line_color=None
p.yaxis.ticker = []

p.quad(
    left='start', 
    right='end', 
    top=1, 
    bottom=0, 
    source=cds,
    color='color',
    legend_field='activity'
)

p.legend.location = 'top_right'
output_file('PredictionGraph.html')
show(p)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 18:48:03