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

如何用Pandas绘制多周数据的stacked bar plot并优化x-axis刻度?

堆叠柱状图绘制及X轴标签优化方案

问题原因

你的原始数据集是长格式(每个Week对应多条Instrument记录),直接调用df.plot.bar(stacked=True)无法生成堆叠效果——因为pandas会把每一行都当作独立的柱子,而非按Week聚合堆叠不同Instrument的数值。

解决步骤

1. 转换数据为宽格式

使用pivot方法将数据重构为宽格式:Week作为索引,Instrument作为列,Trader Count作为对应值。

import pandas as pd
import matplotlib.pyplot as plt

# 假设数据已加载到df变量中
pivot_df = df.pivot(
    index='Week',
    columns='Instrument',
    values='Trader Count'
)

2. 绘制堆叠柱状图

基于转换后的宽格式数据绘制堆叠图:

ax = pivot_df.plot.bar(stacked=True, figsize=(20, 10))

3. 优化X轴标签间隔

针对52周的密集标签,通过设置xticks控制显示间隔(示例为每2周显示一个标签,可根据需求调整):

# 每2周显示一个标签,rotation=0避免标签倾斜
plt.xticks(
    ticks=range(0, len(pivot_df.index), 2),
    labels=pivot_df.index[::2],
    rotation=0
)
plt.tight_layout()  # 自动调整布局,避免标签被截断
plt.show()

完整示例代码

import pandas as pd
import matplotlib.pyplot as plt

# 模拟你的数据集
data = {
    'Week': [1,1,1,2,2,2],
    'Instrument': ['Stock','Bond','MBS','Stock','Bond','MBS'],
    'Trader Count': [100,50,20,150,500,200]
}
df = pd.DataFrame(data)

# 数据转换
pivot_df = df.pivot(index='Week', columns='Instrument', values='Trader Count')

# 绘图及标签优化
ax = pivot_df.plot.bar(stacked=True, figsize=(20, 10))
plt.xticks(ticks=range(0, len(pivot_df.index), 2), labels=pivot_df.index[::2], rotation=0)
plt.tight_layout()
plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 06:03:12