在 matplotlib 中使用线图时用日期替换 X 轴上的数字

replace numbers on X axis with dates when using line plot in matplotlib

我正在用数字数组绘制直线图

fig, ax = plt.subplots()
ax.plot(x, 0 * x)

x 是数组:

array([  0,1,2,3,4,5,6,7,8,9,10 ])

这条线很好,但我想在 x 轴上显示日期。我想关联 每个数字的日期并将其用作我的 x 刻度。

任何人都可以提出建议吗?

你可以控制the ticker format of any value using a ticker.FuncFormatter:

import matplotlib.ticker as ticker
def todate(x, pos, today=DT.date.today()):
    return today+DT.timedelta(days=x)
fmt = ticker.FuncFormatter(todate)
ax.xaxis.set_major_formatter(fmt)

如果日期太拥挤,您可以轮换:

fig.autofmt_xdate(rotation=45)  

例如,

import datetime as DT
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import matplotlib.ticker as ticker

x = np.array([0,1,2,3,4,5,6,7,8,9,10])

fig, ax = plt.subplots(figsize=(7, 4))
ax.plot(x, x**2*np.exp(-x))
def todate(x, pos, today=DT.date.today()):
    return today+DT.timedelta(days=x)
fmt = ticker.FuncFormatter(todate)
ax.xaxis.set_major_formatter(fmt)
fig.autofmt_xdate(rotation=45)  
plt.show()

产量