Pandas / matplotlib 将 2018 和 2019 年显示为 48 和 49

sta*_*010 7 python matplotlib pandas

我正在使用 Pandas 在单个图表中绘制具有两个时间序列的数据框。但是,年份信息以奇怪的数字出现。2018 年和 2019 年在 x 轴上分别为 48 和 49。例如,日期 05-01-2018 变为 05-01-48。请参阅此问题底部的图。

我的问题与此问题类似,但该问题的解决方案说使用 matplotlibplot()而不是 Pandas 的df.plot()函数。我更喜欢使用,df.plot()因为它可以轻松地将两个时间序列绘制在一起。

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

from matplotlib.dates import MonthLocator, DateFormatter

indx = pd.date_range('2017-04-01', '2019-01-01')
seriesA = pd.Series(np.random.randn(len(indx)), index=indx)
seriesB = pd.Series(np.random.randn(len(indx)), index=indx)
df = pd.DataFrame({'a': seriesA, 'b': seriesB})

df.head()
#                    a         b
# 2017-04-01 -1.191265 -0.268962
# 2017-04-02  1.545406 -0.805481
# 2017-04-03  0.022768 -1.412308
# 2017-04-04 -2.024388  0.268758
# 2017-04-05  0.900840 -1.654095

ax = df.plot(y=['a', 'b'], figsize=(12,7))

xtick_locator = MonthLocator(interval=1)
xtick_dateformatter = DateFormatter('%m/%d/%Y')
ax.xaxis.set_major_locator(xtick_locator)
ax.xaxis.set_major_formatter(xtick_dateformatter)
ax.autoscale_view()
_ = plt.xticks(rotation=90, )
_ = plt.grid()
_ = plt.xlabel('')
_ = plt.ylim(0)

_ = plt.show()
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

Par*_*ait 1

考虑使用plt.FixedFormatterpandas 每月的日期resample。下面使用 2017 年开始的发布数据。

# RESAMPLE SERIES (TAKING INDEX VALUES)
x_dates = pd.Series(df.resample('MS').max().index).dt.strftime('%m/%d/%Y')
# ASSIGN AS AXIS TICKS
ax.xaxis.set_major_formatter(plt.FixedFormatter(x_dates))
ax.set_xticklabels(labels=x_dates, rotation=45, ha='center')

xtick_locator = MonthLocator(interval=1)    
ax.xaxis.set_major_locator(xtick_locator)

plt.autoscale(enable=True, axis='x', tight=True)

ax.autoscale_view()
_ = plt.xticks(rotation=90, ha='center')
_ = plt.grid()
_ = plt.xlabel('')
_ = plt.ylim(0)
_ = plt.show()
Run Code Online (Sandbox Code Playgroud)

时间序列图输出