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

Pandas绘制堆叠柱状图时X轴日期月份显示错误的解决咨询

解决Pandas堆叠柱状图X轴日期显示错误的问题

问题根源:Pandas绘制柱状图时,会将datetime索引转换为类别型的位置索引(即x轴实际是0、1、2...这样的整数),而非保留原始的datetime值。所以用mdates.DateFormatter格式化时,会把这些整数当作Unix时间戳解析,自然得到1970年的日期。

方法一:手动设置X轴标签(最简方案)

直接提取datetime索引的月份缩写,替换x轴默认标签:

import matplotlib.pyplot as plt
import pandas as pd
from datetime import datetime

df = pd.DataFrame({'value1':[1,2], 'value2':[5,4]},
                   index=[datetime(year=2020, month=3, day=3),
                          datetime(year=2020, month=4, day=6)])

# 绘制堆叠柱状图
ax = df.plot(kind='bar', stacked=True)
# 替换x轴标签为对应月份缩写
ax.set_xticklabels(df.index.strftime('%b'))
plt.show()

如果需要显示年份+月份(如Mar 2020),可将'%b'改为'%b %Y'。

方法二:用Matplotlib原生API绘制(更灵活)

绕过Pandas的plot方法,直接控制柱子位置与标签:

import matplotlib.pyplot as plt
import pandas as pd
from datetime import datetime

df = pd.DataFrame({'value1':[1,2], 'value2':[5,4]},
                   index=[datetime(year=2020, month=3, day=3),
                          datetime(year=2020, month=4, day=6)])

x = range(len(df))
width = 0.8

# 绘制第一层柱子
plt.bar(x, df['value1'], width, label='value1')
# 绘制第二层堆叠柱子
plt.bar(x, df['value2'], width, bottom=df['value1'], label='value2')

# 设置x轴标签为月份
plt.xticks(x, df.index.strftime('%b'))
plt.legend()
plt.show()

方法三:利用Pandas DatetimeIndex的dt属性

若索引为DatetimeIndex,可直接通过dt属性生成标签:

import matplotlib.pyplot as plt
import pandas as pd
from datetime import datetime

df = pd.DataFrame({'value1':[1,2], 'value2':[5,4]},
                   index=pd.to_datetime([datetime(year=2020, month=3, day=3),
                                         datetime(year=2020, month=4, day=6)]))

ax = df.plot(kind='bar', stacked=True)
# 通过dt属性获取月份缩写
ax.set_xticklabels(df.index.strftime('%b'))
plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 10:47:18