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

Python Bokeh堆叠分组hbar_stack甘特图自定义颜色控制问题

Bokeh hbar_stack自定义单条颜色实现方案

要实现对18个堆叠条形的单独颜色控制,你可以直接给hbar_stack的color参数传入和每个数据条目对应的颜色列表,以下是修改后的完整可运行代码:

from bokeh.io import output_notebook
from bokeh.models import ColumnDataSource, FactorRange
from bokeh.plotting import figure, show

output_notebook()

starts = []
durations = []
Task1 = {'P1': (1, 9), 'P2': (2, 8), 'P3':(3, 7)}
Task2 = {'P1': (4 ,6), 'P2': (5, 5), 'P3':(6, 4)}
Task3 = {'P1': (7, 3), 'P2': (8, 2), 'P3':(9, 1)}

for value in Task1.values():
    starts.append(value[0])
    durations.append(value[1])
for value in Task2.values():
    starts.append(value[0])
    durations.append(value[1])
for value in Task3.values():
    starts.append(value[0])
    durations.append(value[1])    

factors = [
            ('Task 3', 'P1'), ('Task 3', 'P2'), ('Task 3', 'P3'),
            ('Task 2', 'P1'), ('Task 2', 'P2'), ('Task 2', 'P3'),
            ('Task 1', 'P1'), ('Task 1', 'P2'), ('Task 1', 'P3')
            ]

regions = ['start', 'duration']

source = ColumnDataSource(data=dict(
    y=factors,
    start =  starts,
    duration = durations
))

# 自定义颜色配置
# 1. 定义P分类对应的颜色,可按需修改
p_color_map = {
    'P1': '#27ae60',
    'P2': '#2980b9',
    'P3': '#c0392b'
}
# 2. start层全部设为透明
start_colors = ["rgba(0,0,0,0)"] * len(factors)
# 3. duration层按P分类匹配颜色,也可以手动逐个设置列表元素实现单条自定义
duration_colors = [p_color_map[factor[1]] for factor in factors]

p = figure(y_range=FactorRange(*factors), plot_height=250,
           toolbar_location=None)

# 传入分层的颜色列表
p.hbar_stack(regions, y='y', width=0.9, alpha=0.8, 
             color=[start_colors, duration_colors], 
             source=source,
             legend_label = regions)

p.x_range.start = 0
p.x_range.end = 18
p.y_range.range_padding = .1
p.xaxis.major_label_orientation = 1
p.xgrid.grid_line_color = 'black'
p.legend.location = "right"
p.legend.orientation = "horizontal"
p.toolbar_location="below"

show(p)

方案说明

  • 所有start对应的条形通过全透明色值rgba(0,0,0,0)实现隐藏效果,符合你的需求
  • 9个duration条形的颜色通过列表duration_colors控制,列表顺序和factors的顺序一一对应,你可以直接修改列表中任意位置的色值,实现18个条形(9个start+9个duration)的完全独立颜色控制。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 06:48:01