在 matplotlib 中对日期范围使用 axvspan

Maa*_*en 7 python date time-series matplotlib

我想绘制一些随季节变化的时间序列,并使用 axvspan 将冬季的部分阴影与夏季的部分阴影不同。我正在使用pyplot.plot_date。我的 y 值是一个 np 浮点数组,我的 x 值是一个使用转换的日期时间对象的 np 数组

    datetime.strptime(date, '%m-%d-%Y'). 
Run Code Online (Sandbox Code Playgroud)

我想使用pyplot.axvspan来应用阴影,但它似乎只适用于 x 轴的常规数字,而我的 x 轴是日期。我遇到的错误是

    ValueError: view limit minimum -36858.05 is less than 1 and is an invalid Matplotlib date value. This often happens if you pass a non-datetime value to an axis that has datetime units
Run Code Online (Sandbox Code Playgroud)

有什么办法可以解决这个问题?

Imp*_*est 13

在 matplotlib 日期时间轴中也使用数字,

Matplotlib 使用浮点数表示日期,指定自 0001-01-01 UTC 以来的天数加 1。

许多功能,如plotscatterbar等自动转换datetime对象,以这些数字,而许多辅助功能,比如axvspan,没有这样做,自动转换到最新版本的matplotlib的。

所以在 matplotlib 3 中你可以很容易地做到

ax.axvspan(datetime(2019,3,1), datetime(2019,3,31))
Run Code Online (Sandbox Code Playgroud)

但是如果使用旧版本你需要手动完成,使用matplotlib.dates.date2num,例如

ax.axvspan(date2num(datetime(2019,3,1)), date2num(datetime(2019,3,31)))
Run Code Online (Sandbox Code Playgroud)

一些完整的例子:

from datetime import datetime
import matplotlib.pyplot as plt
from matplotlib.dates import date2num

fig, ax = plt.subplots()

ax.plot([datetime(2019,2,14), datetime(2019,4,26)], [1,2])

ax.axvspan(date2num(datetime(2019,3,1)), date2num(datetime(2019,3,31)), 
           label="March", color="crimson", alpha=0.3)

ax.legend()
fig.autofmt_xdate()
plt.show()
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明