简体   繁体   English

使用日期作为 x 轴的不断增长的 matplotlib 条形图

[英]Growing matplotlib bar chart using dates as an x-axis

I have some code that should, in theory, save an image of a bar chart that grows by thirty days each time a loop completes, here is the code:我有一些代码,理论上应该保存一个条形图的图像,每次循环完成时都会增加 30 天,这是代码:

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

f, ax = plt.subplots()
ax.xaxis.set_major_locator(mdates.YearLocator(1))
ax.xaxis_date()

xi = dt.datetime(1900,1,1)
xf = dt.datetime(1910,1,1)

x = xi
num = 0

while x < xf:
    #add 30 days to the current date
    x += dt.timedelta(30)

    #tranform datetime data into matplotlib number dates
    xmin = mdates.date2num(xi)
    xmax = mdates.date2num(x)

    #plot the bar graph that should grow by 30 days each loop
    ax.broken_barh([(xmin,xmax-xmin)], (0,1))

    #save the figure as a frame
    plt.savefig("frame-{}.png".format(num))
    num += 1

The problem is that I get a AttributeError: 'numpy.float64' object has no attribute 'toordinal' error every time I try to run it.问题是我每次尝试运行它时都会收到AttributeError: 'numpy.float64' object has no attribute 'toordinal'错误。 I use this exact same code to create a plot that does not grow outside of a loop and it works.我使用这个完全相同的代码来创建一个不会在循环之外增长的图并且它可以工作。 When I remove the ax.xaxis_date() portion of the code it works, except the x-axis of the chart is not formatted as a date.当我删除代码的ax.xaxis_date()部分时,它可以工作,但图表的 x 轴未格式化为日期。

I have another place where I use similar code, basically the same without the loop or the growing variable, and it works even with the ax.xaxis_date() function.我在另一个地方使用了类似的代码,基本相同,没有循环或增长变量,它甚至可以与ax.xaxis_date()函数一起使用。

I've been troubleshooting this for a really long time and can't seem to figure it out, any help would be much appreciated.我已经解决这个问题很长时间了,似乎无法弄清楚,任何帮助将不胜感激。 Thanks!谢谢!

I have run your code as-is, simple copy-paste and it worked for me.我已经按原样运行了你的代码,简单的复制粘贴,它对我有用。 It produced files named frame-*.png, * going from 0 to 121. I attach the first and final files below.它生成了名为 frame-*.png, * 从 0 到 121 的文件。我在下面附上了第一个和最终文件。

I am using Python 3.6.8 on Ubuntu 18.04.3 LTS with matplotlib 3.1.2.我在 Ubuntu 18.04.3 LTS 和 matplotlib 3.1.2 上使用 Python 3.6.8。

在此处输入图片说明 在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM