在 X 轴上绘制日期

我正在试图根据日期绘制信息。我有一个日期列表格式为“01/02/1991”。

我通过以下方式转化了它们:

x = parser.parse(date).strftime('%Y%m%d'))

也就是 19910102

然后我试着用 num2date

import matplotlib.dates as dates
new_x = dates.num2date(x)

图示:

plt.plot_date(new_x, other_data, fmt="bo", tz=None, xdate=True)

但我得到了一个错误。它说“价值错误: 年超出范围”。有什么解决方案吗?

321932 次浏览

As @KyssTao has been saying, help(dates.num2date) says that the x has to be a float giving the number of days since 0001-01-01 plus one. Hence, 19910102 is not 2/Jan/1991, because if you counted 19910101 days from 0001-01-01 you'd get something in the year 54513 or similar (divide by 365.25, number of days in a year).

Use datestr2num instead (see help(dates.datestr2num)):

new_x = dates.datestr2num(date) # where date is '01/02/1991'

You can do this more simply using plot() instead of plot_date().

First, convert your strings to instances of Python datetime.date:

import datetime as dt


dates = ['01/02/1991','01/03/1991','01/04/1991']
x = [dt.datetime.strptime(d,'%m/%d/%Y').date() for d in dates]
y = range(len(x)) # many thanks to Kyss Tao for setting me straight here

Then plot:

import matplotlib.pyplot as plt
import matplotlib.dates as mdates


plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%m/%d/%Y'))
plt.gca().xaxis.set_major_locator(mdates.DayLocator())
plt.plot(x,y)
plt.gcf().autofmt_xdate()

Result:

enter image description here

I have too low reputation to add comment to @bernie response, with response to @user1506145. I have run in to same issue.

1

The answer to it is an interval parameter which fixes things up

2

import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import numpy as np
import datetime as dt


np.random.seed(1)


N = 100
y = np.random.rand(N)


now = dt.datetime.now()
then = now + dt.timedelta(days=100)
days = mdates.drange(now,then,dt.timedelta(days=1))


plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
plt.gca().xaxis.set_major_locator(mdates.DayLocator(interval=5))
plt.plot(days,y)
plt.gcf().autofmt_xdate()
plt.show()

Adapting @Jacek Szałęga's answer for the use of a figure fig and corresponding axes object ax:

import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import numpy as np
import datetime as dt


np.random.seed(1)


N = 100
y = np.random.rand(N)


now = dt.datetime.now()
then = now + dt.timedelta(days=100)
days = mdates.drange(now,then,dt.timedelta(days=1))




fig = plt.figure()
ax = fig.add_subplot(111)
    

ax.plot(days,y)
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
ax.xaxis.set_major_locator(mdates.DayLocator(interval=5))
ax.tick_params(axis='x', labelrotation=45)


plt.show()