使用 Python 的 matplotlib 在 x 轴上绘制日期 [英] Plotting dates on the x-axis with Python's matplotlib

查看:80
本文介绍了使用 Python 的 matplotlib 在 x 轴上绘制日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试根据日期绘制信息.我有一个格式为01/02/1991"的日期列表.

I am trying to plot information against dates. I have a list of dates in the format "01/02/1991".

我通过执行以下操作转换它们:

I converted them by doing the following:

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

它给出了 19910102

然后我尝试使用 num2date

Then I tried to use 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:年份超出范围".有什么解决办法吗?

But I get an error. It says "ValueError: year is out of range". Any solutions?

推荐答案

正如@KyssTao 所说,help(dates.num2date)x 必须是一个浮点数,给出自 0001-01-01 以来的天数加一.因此,19910102 不是 2/Jan/1991,因为如果你从 0001-01-01 算起 19910101 天,你会得到 54513 年或类似的东西(除以 365.25,天数在一年).

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

改用datestr2num(参见help(dates.datestr2num)):

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

这篇关于使用 Python 的 matplotlib 在 x 轴上绘制日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆