一般来说,pandas 和 matplotlib 的日期时间实用程序是不兼容的。因此,在使用 pandas 创建的日期轴上尝试使用 matplotlib.dates 对象在大多数情况下都会失败。
一个原因是例如来自the documentation
datetime 对象被转换为浮点数,表示自 0001-01-01 UTC 以来的天数,加 1。例如,0001-01-01, 06:00 是 1.25,而不是 0.25。
但是,这不是唯一的区别,因此建议不要将 pandas 和 matplotlib 混合使用来处理 datetime 对象。
但是,可以选择告诉 pandas 不要使用自己的日期时间格式。在这种情况下,可以使用 matplotlib.dates 代码。这可以通过。
df.plot(x_compat=True)
由于 pandas 不提供复杂的日期格式化功能,因此可以使用 matplotlib 进行绘图和格式化。
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as dates
df = pd.DataFrame({'date':['20170527','20170526','20170525'],'ratio1':[1,0.98,0.97]})
df['date'] = pd.to_datetime(df['date'])
usePandas=True
#Either use pandas
if usePandas:
df = df.set_index('date')
df.plot(x_compat=True)
plt.gca().xaxis.set_major_locator(dates.DayLocator())
plt.gca().xaxis.set_major_formatter(dates.DateFormatter('%d\n\n%a'))
plt.gca().invert_xaxis()
plt.gcf().autofmt_xdate(rotation=0, ha="center")
# or use matplotlib
else:
plt.plot(df["date"], df["ratio1"])
plt.gca().xaxis.set_major_locator(dates.DayLocator())
plt.gca().xaxis.set_major_formatter(dates.DateFormatter('%d\n\n%a'))
plt.gca().invert_xaxis()
plt.show()
- 使用 matplotlib 面向对象的 API 更新
usePandas=True
#Either use pandas
if usePandas:
df = df.set_index('date')
ax = df.plot(x_compat=True, figsize=(6, 4))
ax.xaxis.set_major_locator(dates.DayLocator())
ax.xaxis.set_major_formatter(dates.DateFormatter('%d\n\n%a'))
ax.invert_xaxis()
ax.get_figure().autofmt_xdate(rotation=0, ha="center")
# or use matplotlib
else:
fig, ax = plt.subplots(figsize=(6, 4))
ax.plot('date', 'ratio1', data=df)
ax.xaxis.set_major_locator(dates.DayLocator())
ax.xaxis.set_major_formatter(dates.DateFormatter('%d\n\n%a'))
fig.invert_xaxis()
plt.show()