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

使用Bokeh绘制的柱状图始终呈灰色,求排查解决方法

Bokeh柱状图显示灰色的解决方法

问题场景

用Bokeh从pandas DataFrame绘制英国选举结果的垂直柱状图,参考示例代码后,所有柱子始终显示为灰色,无法按政党匹配预设的颜色。

问题根源

颜色映射逻辑错误:你原本基于年份+政党的组合元组字段'x'使用factor_cmap,但Bokeh无法正确从这个复合元组中提取政党信息来匹配颜色表。此外,用iterrows()遍历构造x轴数据的方式既低效又容易引入问题。

修正后的完整代码

import pandas as pd
from bokeh.io import output_file, show
from bokeh.models import ColumnDataSource, FactorRange
from bokeh.plotting import figure
from bokeh.transform import factor_cmap

# 读取CSV数据(分隔符为分号)
df1 = pd.read_csv('uk-election-results1.csv', sep=';')
output_file("elections.html")

# 构造x轴的因子元组:年份转字符串后与政党组合
df1['year_str'] = df1['year'].astype(str)
x = list(zip(df1['year_str'], df1['party']))

# 构造数据源:单独加入party字段用于颜色映射
source = ColumnDataSource(data={
    'x': x,
    'y': df1['seats'],
    'party': df1['party']
})

# 政党对应的颜色映射表
color_map = {
    'Conservative':'#0343df',
    'Labour':'#e50000',
    'Liberal':'#ffff14',
    'Others':'#929591'
}

# 直接基于party字段生成颜色映射
fill_color = factor_cmap(
    field_name='party',
    palette=list(color_map.values()),
    factors=list(color_map.keys())
)

# 创建图表
p = figure(x_range=FactorRange(*x), width=2000, title="英国议会选举结果")
p.vbar(x='x', top='y', width=0.9, source=source, fill_color=fill_color, line_color=fill_color)

# 图表样式调整
p.y_range.start = 0
p.x_range.range_padding = 0.1
p.yaxis.axis_label = '获得议席数'
p.xaxis.major_label_orientation = 1
p.xgrid.grid_line_color = None

show(p)

核心修改说明

  • 新增party字段到数据源:把df1['party']单独放入ColumnDataSource,让factor_cmap可以直接基于政党名称匹配对应颜色,这是解决灰色柱子的关键。
  • 简化x轴数据构造:用zip配合pandas的列直接生成元组列表,替代低效的iterrows()遍历。
  • 优化颜色映射逻辑:移除factor_cmap中不必要的start和end参数,直接针对单一字段做映射,逻辑更清晰。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 13:15:32