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

如何在Pandas堆叠柱状图上叠加绘制滚动平均线?

堆叠柱状图叠加滚动平均线的问题解决

问题重现

要绘制每日各分类事件发生数量的堆叠柱状图,同时叠加总数量的7日滚动平均线,相关代码如下:

数据构造

import pandas as pd
import numpy as np

date_range = pd.date_range(start='2023-01-01', periods=10)
data = {
    'Category A': np.random.randint(1, 10, 10),
    'Category B': np.random.randint(1, 10, 10),
}
df = pd.DataFrame(data, index=date_range)

计算滚动平均线

df['total'] = df.sum(axis=1)
df['rolling'] = df['total'].rolling(window=7).mean()

尝试绘图的代码

ax = df[['Category A', 'Category B']].plot(kind='bar', stacked=True)
df['rolling'].plot(kind='line', ax=ax)

运行后仅能看到折线图,堆叠柱状图被隐藏,alpha参数无法解决该问题。

问题原因

堆叠柱状图的x轴为分类轴(日期被转化为离散分类标签),而折线图默认使用连续日期轴,两者坐标体系不匹配,导致柱状图被折线图覆盖或位置错位。

解决方法

方法1:指定折线图使用分类轴

绘制折线图时添加use_index=False参数,让其对齐柱状图的分类x轴位置:

ax = df[['Category A', 'Category B']].plot(kind='bar', stacked=True)
df['rolling'].plot(kind='line', ax=ax, use_index=False, marker='o', color='red')

方法2:手动设置折线图的x坐标

获取柱状图的柱子中心位置,将折线图的x轴绑定到这些位置:

ax = df[['Category A', 'Category B']].plot(kind='bar', stacked=True)
# 获取每个柱子的中心坐标
x_positions = [patch.get_x() + patch.get_width()/2 for patch in ax.patches]
# 绘制对齐的折线图
ax.plot(x_positions, df['rolling'], marker='o', color='red')

美化示例

可以添加样式优化,让图表更清晰:

ax = df[['Category A', 'Category B']].plot(kind='bar', stacked=True, figsize=(10,6))
df['rolling'].plot(kind='line', ax=ax, use_index=False, marker='o', color='#ff3333', linewidth=2, label='7日滚动平均')
ax.set_ylabel('事件数量')
ax.set_xlabel('日期')
ax.legend()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 18:55:55