在 x 轴上绘制日期

问题描述 投票:0回答:5

我正在尝试根据日期绘制信息。我有一个格式为“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)

但是我收到错误。它说“ValueError:年份超出范围”。有什么解决办法吗?

python datetime matplotlib
5个回答
190
投票

您可以使用

plot()
而不是
plot_date()
来更简单地完成此操作。

首先,将字符串转换为 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

然后情节:

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()

结果:

enter image description here


85
投票

我的声誉太低,无法在 @bernie 回复中添加评论,并回复 @user1506145。我遇到了同样的问题。

1

答案是一个区间参数来解决问题

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()

27
投票

正如 @KyssTao 所说,

help(dates.num2date)
表示
x
必须是一个浮点数,给出自 0001-01-01 以来的天数加一。因此,
19910102
不是 2/Jan/1991,因为如果您从 0001-01-01 算起 19910101 天,您会得到 54513 年或类似年份的数据(除以 365.25,一年中的天数)。

使用

datestr2num
代替(参见
help(dates.datestr2num)
):

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

3
投票

调整@Jacek Szałęga的答案以使用图形

fig
和相应的轴对象
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()

1
投票
date = raw_date[:20]
# plot lines
plt.plot(date,target[:20] , label = "Real")
plt.xlabel('Date', fontsize=10)
plt.ylabel('Ylabel', fontsize=10)
plt.legend()
plt.title('Date to show')
plt.xticks(date_to_show_as_list,rotation=90)
plt.figure().set_figwidth(30)
plt.show()
© www.soinside.com 2019 - 2024. All rights reserved.