【问题标题】:How to plot timedelta as value with matplotlib如何使用 matplotlib 将 timedelta 绘制为值
【发布时间】:2016-11-23 12:57:51
【问题描述】:

我正在尝试针对某些迭代值绘制以秒为单位的持续时间。我通过减去两个日期时间值来计算持续时间值。然后,我想使用现有工具以非常简单的方式绘制这些结果。

我的代码如下,但还不行:

#!/usr/bin/env python

import datetime
import matplotlib.pyplot as plt
from numpy import arange

it = arange(10)
durations = [datetime.timedelta(hours=h+30) for h in it]

plt.plot(it, durations)

plt.show()

我收到以下错误:

TypeError: float() argument must be a string or a number

我知道我可以通过使用 datetime 而不是 timedelta 来使其工作,但我的目标是以小时为单位(大约 40 小时)绘制持续时间,因此渲染效果不佳。

【问题讨论】:

    标签: python matplotlib timedelta


    【解决方案1】:

    这是因为没有定义 timedelta 到 float 的转换。您可以使用:

    durations = [datetime.timedelta(hours=h+30).total_seconds()/3600.0 for h in it]
    

    将持续时间转换为浮点小时数。如果你想在你的情节上使用漂亮的小时符号,看看如何format你的刻度标签。您可以将小时(浮点数)转换为格式良好的小时字符串。

    (编辑:将.total_seconds 更改为.total_seconds()

    【讨论】:

    • 不应该是timedelta.total_seconds(),否则你只会得到以一天为模的持续时间?
    猜你喜欢
    • 1970-01-01
    • 2014-08-22
    • 2020-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多