如何用Bokeh实现美国财政部税收数据的堆叠柱状图?
Bokeh堆叠柱状图实现方案
前置准备
假设你的DataFrame名为tax_data,包含核心列:record_date(日期)、transaction_today_amt(当日交易金额)、transaction_catg(交易分类)。
步骤1:导入依赖库
import pandas as pd from bokeh.plotting import figure, show, output_file from bokeh.models import ColumnDataSource from bokeh.palettes import Category20
步骤2:数据预处理
- 确保日期列是datetime类型,非则转换:
tax_data['record_date'] = pd.to_datetime(tax_data['record_date'])
- 将日期转为字符串格式(适配Bokeh的轴渲染,也可直接用datetime类型):
tax_data['record_str'] = tax_data['record_date'].dt.strftime('%Y-%m-%d')
- 按日期+分类分组汇总金额(若数据已按日分类汇总可跳过):
grouped_data = tax_data.groupby(['record_str', 'transaction_catg'])['transaction_today_amt'].sum().unstack().fillna(0)
- 构建Bokeh数据源:
categories = grouped_data.columns.tolist() dates = grouped_data.index.tolist() source = ColumnDataSource(data=dict( x=dates, **{cat: grouped_data[cat].tolist() for cat in categories} ))
步骤3:绘制堆叠柱状图
# 初始化绘图对象 p = figure( x_range=dates, title='2005年至今税收存款分类堆叠柱状图', x_axis_label='记录日期', y_axis_label='当日交易金额', tools='pan,box_zoom,reset,save' ) # 分配分类颜色 colors = Category20[len(categories)] if len(categories) <= 20 else Category20[20] # 绘制堆叠柱 p.vbar_stack( categories, x='x', width=0.8, color=colors, source=source, legend_label=categories ) # 优化图表交互与样式 p.legend.location = 'top_left' p.legend.click_policy = 'hide' # 点击图例可隐藏对应分类系列 p.xaxis.major_label_orientation = 3.14/4 # 旋转x轴标签避免重叠 # 输出与展示 output_file('tax_deposit_stack.html') # 保存为HTML文件 show(p) # 直接在浏览器打开图表
补充说明
- 若交易分类超过20种,可替换调色板为
Category20b/Category20c,或自定义颜色列表。 - 数据量过大时,可添加
DateRangeSlider组件实现日期范围筛选,提升交互体验。 - 需确保
transaction_today_amt为数值类型,非则执行转换:
tax_data['transaction_today_amt'] = pd.to_numeric(tax_data['transaction_today_amt'], errors='coerce')
内容的提问来源于stack exchange,提问作者dharmatech
相关产品推荐
相关产品推荐

