【问题标题】:Growing matplotlib bar chart using dates as an x-axis使用日期作为 x 轴增长 matplotlib 条形图
【发布时间】:2019-11-26 02:08:22
【问题描述】:

我有一些代码理论上应该保存一个条形图的图像,每次循环完成时都会增长三十天,这里是代码:

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

问题是我每次尝试运行它时都会收到AttributeError: 'numpy.float64' object has no attribute 'toordinal' 错误。我使用这个完全相同的代码来创建一个不会在循环之外增长的图并且它可以工作。当我删除代码的 ax.xaxis_date() 部分时,它可以工作,除了图表的 x 轴未格式化为日期。

我在另一个地方使用了类似的代码,基本相同,没有循环或不断增长的变量,它甚至可以使用ax.xaxis_date() 函数。

我已经对此进行了很长时间的故障排除,但似乎无法弄清楚,任何帮助将不胜感激。谢谢!

【问题讨论】:

  • 能否为您的问题添加异常堆栈跟踪?

标签: python datetime matplotlib


【解决方案1】:

我已按原样运行您的代码,简单的复制粘贴,它对我有用。它生成了名为 frame-*.png, * 的文件,从 0 到 121。我在下面附上第一个和最后一个文件。

我在 Ubuntu 18.04.3 LTS 上使用 Python 3.6.8 和 matplotlib 3.1.2。

【讨论】:

  • 天哪!我刚刚更新了 matplotlib,它现在完全可以工作了,我什至没有想过要这样做。谢谢!
  • 不用担心,有时它比想象的要简单。由于您是该网站的新贡献者,请随时阅读此处 (stackoverflow.com/help/someone-answers),了解当收到有人提出的问题的答案时应该做什么。
猜你喜欢
  • 1970-01-01
  • 2018-05-20
  • 2020-03-24
  • 2020-11-20
  • 2019-03-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-23
相关资源
最近更新 更多