简体   繁体   English

使用 matplotlib 绘制熊猫系列时更改日期标签

[英]Change date labels when plotting pandas series with matplotlib

I have a time series of monthly data like this, and plot it like this:我有一个这样的月度数据时间序列,并将其绘制如下:

rng = pd.date_range('1965-01-01', periods=600, freq='M')
ts = pd.Series(np.random.randn(len(rng)), index=rng)
fig, ax = plt.subplots()
ts.plot(ax=ax)

The major tick marks are set every 10 years, beginning in 1969. I'd like to change this so they start in 1975. After looking at some matplotlib samples ( here and here ) I tried adding主要刻度线每 10 年设置一次,从 1969 年开始。我想改变这一点,所以他们从 1975 年开始。在查看了一些 matplotlib 样本(这里这里)后,我尝试添加

from matplotlib.dates import YearLocator, DateFormatter
decs = YearLocator(10)   # decades
decsFmt = DateFormatter("%Y")

ax.xaxis.set_major_locator(decs)
ax.xaxis.set_major_formatter(decsFmt)

datemin = pd.datetime(ts.index.min().year, 1, 1)
datemax = pd.date(ts.index.max().year + 1, 1, 1)
ax.set_xlim(datemin, datemax)

but this doesn't work.但这不起作用。

If you want to use matplotlib to set axis limits you will need to turn off pandas' date formatting.如果要使用 matplotlib 设置轴限制,则需要关闭 Pandas 的日期格式。

Just change the line to只需将行更改为

ts.plot(x_compat=True, ax=ax)

and it should work.它应该工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM