用Python的matplotlib在x轴上绘制日期(Plotting dates on the x

编程入门 行业动态 更新时间:2024-10-06 01:39:56
用Python的matplotlib在x轴上绘制日期(Plotting dates on the x-axis with Python's matplotlib)

我试图根据日期绘制信息。 我有一个格式为“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:年度超出范围”。 任何解决方案

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

which gives 19910102

Then I tried to use num2date

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

Plotting:

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

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

最满意答案

正如@KyssTao一直在说的, help(dates.num2date)表示x必须是一个浮点数,给出0001-01-01以后的天数加上1。 因此, 19910102不是1991年1月2日,因为如果你从0001-01-01算起19910101天,你会得到54513年或类似年份(除以365.25,一年中的天数)。

改为使用datestr2num (请参阅help(dates.datestr2num) ):

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

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'

更多推荐

本文发布于:2023-08-07 10:56:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1464117.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:日期   matplotlib   Python   Plotting   dates

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!