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

如何调整柱状图X轴刻度并扩展时间范围至2009年

堆叠柱状图扩展时间范围与自定义X轴刻度解决方案

问题说明

我有一个名为barras的DataFrame,包含2017-2022年月度数据,列名分别为% PRINCIPAL、% APORTES、% ΔE。绘制堆叠柱状图时需要实现两个需求:

  • 扩展时间范围至2009年,无数据的月份也要保留柱状位置
  • X轴仅显示每年1月和6月的刻度

DataFrame样例

% PRINCIPAL  % APORTES       % ΔE
FECHA                                     
2017-03    25.974253  42.430129  31.595618
2017-04   131.728602  27.057582 -58.786184
2017-05   144.069530  17.564611 -61.634142
2017-06   116.492102  25.948196 -42.440299
2017-07    95.677079  42.383666 -38.060745
             ...        ...        ...
2022-05    86.728444  46.208640 -32.937084
2022-06    87.980394  58.643608 -46.624002
2022-07    73.873644  53.591839 -27.465483
2022-08    72.113597  44.375137 -16.488734
2022-09    52.777619  79.301887 -32.079506

原有绘图代码

barras = pd.concat([I['% PRINCIPAL'],I['% APORTES'],I['% ΔE']], axis=1)
barras.index = pd.to_datetime(barras.index).strftime('%Y-%m')
barras.plot(kind="bar",stacked=True, color = ['b','g','r'], edgecolor='black', width=1, alpha=0.77, figsize=(16,8))
plt.title('PORCENTAJES DE CAUDAL EN TRAMO I')
plt.ylabel("Caudal (%)")
plt.xlabel('Fecha')
plt.legend(loc='best')
plt.savefig("BLOQUE I.png", bbox_inches="tight", dpi=160)

效果对比

  • 现有效果:X轴仅显示2017-2022年的所有月份刻度,时间范围未扩展至2009年
  • 期望效果:时间范围覆盖2009-2022年,X轴仅标注每年1月和6月,无数据月份保留空柱状位置

解决步骤

1. 扩展时间索引

将原始DataFrame的索引转为datetime类型,再生成2009年1月至2022年9月的完整月度序列,用reindex填充缺失数据:

import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

# 处理原始数据,转换索引为datetime类型
barras = pd.concat([I['% PRINCIPAL'],I['% APORTES'],I['% ΔE']], axis=1)
barras.index = pd.to_datetime(barras.index)

# 生成2009-01到2022-09的完整月度时间序列
full_time_index = pd.date_range(start='2009-01', end='2022-09', freq='MS')
barras = barras.reindex(full_time_index)

2. 绘制堆叠柱状图并自定义X轴刻度

改用matplotlib原生方法绘图,精准控制刻度显示:

# 创建画布和轴对象
fig, ax = plt.subplots(figsize=(16, 8))

# 定义柱状宽度(适配月度日期)
bar_width = 25

# 逐层绘制堆叠柱状图
ax.bar(barras.index, barras['% PRINCIPAL'], width=bar_width, color='b', edgecolor='black', alpha=0.77, label='% PRINCIPAL')
ax.bar(barras.index, barras['% APORTES'], width=bar_width, bottom=barras['% PRINCIPAL'], color='g', edgecolor='black', alpha=0.77, label='% APORTES')
ax.bar(barras.index, barras['% ΔE'], width=bar_width, bottom=barras['% PRINCIPAL'] + barras['% APORTES'], color='r', edgecolor='black', alpha=0.77, label='% ΔE')

# 设置X轴刻度:仅显示每年1月和6月
ax.xaxis.set_major_locator(mdates.MonthLocator(bymonth=[1, 6]))
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m'))

# 图表样式调整
ax.set_title('PORCENTAJES DE CAUDAL EN TRAMO I')
ax.set_ylabel("Caudal (%)")
ax.set_xlabel('Fecha')
ax.legend(loc='best')
plt.xticks(rotation=45)  # 旋转刻度避免重叠
plt.tight_layout()

# 保存并显示图表
plt.savefig("BLOQUE I.png", bbox_inches="tight", dpi=160)
plt.show()

关键说明

  • pd.date_range生成完整时间序列,确保2009年起所有月份都被包含,缺失数据自动填充为NaN,绘图时对应位置显示空柱
  • mdates.MonthLocator指定仅显示1月和6月的刻度,结合DateFormatter设置刻度显示格式
  • 用matplotlib原生bar方法绘制堆叠柱,通过bottom参数控制堆叠顺序,相比pandas的plot方法更易实现自定义刻度需求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 09:37:25