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

如何解决Pandas面积图x轴时间轴标签重叠的问题

解决时间序列面积图x轴标签重叠问题(仅显示年份)

前置准备

首先确保DataFrame的索引为datetime类型,这是后续日期刻度设置生效的前提:

import pandas as pd
survived.index = pd.to_datetime(survived.index)

方法1:使用matplotlib日期刻度定位器(最推荐)

直接通过matplotlib的日期工具类指定x轴仅按年显示刻度,可自定义刻度对齐的日期:

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

# 绘制面积图
ax = survived.plot.area(stacked=False)

# 设置x轴主刻度为每年的12月31日(和示例数据的年末时间点对齐)
# 若不需要对齐年末,直接使用mdates.YearLocator()即可,默认对齐每年1月1日
ax.xaxis.set_major_locator(mdates.YearLocator(month=12, day=31))
# 设置刻度显示格式为4位年份
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y'))

# 可选:调整x轴标签旋转角度,进一步避免重叠
plt.xticks(rotation=0)
# 自动调整布局防止标签被截断
plt.tight_layout()

plt.show()

方法2:手动指定刻度位置与标签

如果需要完全自定义显示的年份和对应位置,可以手动提取刻度参数:

import matplotlib.pyplot as plt

# 提取所有出现过的年份,去重后排序
unique_years = sorted(survived.index.year.unique())
# 找到每个年份最后一条数据的索引位置作为刻度位置
tick_positions = [survived.index.get_loc(survived[survived.index.year == y].index[-1]) for y in unique_years]
# 刻度标签设置为年份
tick_labels = [str(y) for y in unique_years]

# 绘图时指定刻度
ax = survived.plot.area(stacked=False, xticks=tick_positions)
ax.set_xticklabels(tick_labels)

plt.tight_layout()
plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 10:57:00