python - 使用 matplotlib 和 python 绘制 datetime.timedelta

标签 python matplotlib plot

我正在执行一项任务,我需要计算每天花费的时间,然后使用条形图表示该时间,因此对于此任务,我使用了 python 并且能够获取每天花费的时间,并将其存储在列表“time_list”中,现在我不明白如何使用 matplotlib 函数绘制它。 问题在于,此列表包含 datetime.timedelta 类值。 示例:

time_list
[datetime.timedelta(0, 23820), datetime.timedelta(0, 27480), datetime.timedelta(0, 28500), datetime.timedelta(0, 24180), datetime.timedelta(0, 27540), datetime.timedelta(0, 28920), datetime.timedelta(0, 28800), datetime.timedelta(0, 29100), datetime.timedelta(0, 29100), datetime.timedelta(0, 24480), datetime.timedelta(0, 27000)]

这些值的含义如下:

Total Time Spent on  2  is  6:37:00
Total Time Spent on  3  is  7:38:00
Total Time Spent on  4  is  7:55:00
Total Time Spent on  5  is  6:43:00
Total Time Spent on  8  is  7:39:00
Total Time Spent on  9  is  8:02:00
Total Time Spent on  10  is  8:00:00
Total Time Spent on  11  is  8:05:00
Total Time Spent on  12  is  8:05:00
Total Time Spent on  15  is  6:48:00
Total Time Spent on  16  is  7:30:00

谁能帮我策划这个。 提前致谢

最佳答案

我不认为你可以在 Matplotlib 中直接绘制 timedelta,但由于你已经有了秒数,你可以定义一个自定义的刻度格式,将秒转换为小时和分钟。

from matplotlib.ticker import FuncFormatter

def format_func(x, pos):
    hours = int(x//3600)
    minutes = int((x%3600)//60)
    seconds = int(x%60)

    return "{:d}:{:02d}".format(hours, minutes)
    # return "{:d}:{:02d}:{:02d}".format(hours, minutes, seconds)

formatter = FuncFormatter(format_func)

然后,您可以为 y 轴设置刻度格式器。

这是一个使用 bar 的例子。

labels = [2, 3, 4, 5, 8, 9, 10, 11, 12, 15, 16]
seconds = [i.seconds for i in time_list]
f = plt.figure()
ax = f.add_subplot(1,1,1)
ax.bar(labels, seconds)

ax.yaxis.set_major_formatter(formatter)
# this locates y-ticks at the hours
ax.yaxis.set_major_locator(matplotlib.ticker.MultipleLocator(base=3600))
# this ensures each bar has a 'date' label
ax.xaxis.set_major_locator(matplotlib.ticker.MultipleLocator(base=1))

Example Bar Graph

关于python - 使用 matplotlib 和 python 绘制 datetime.timedelta,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48294332/

相关文章:

python - 如何计算 Python pandas 数据框中选择值的频率

python-3.x - Seaborn虚线在图例中不是虚线

python - 如何使用 JupyterLab 循环更新交互式图形

python - 如何正确绘制阿累尼乌斯图?

r中散点图的回归线和拟合曲线

python - 如何使 pyplot 窗口大于屏幕并可滚动

python - Pandas DataFrame 按时间戳分组

r - Shiny/ggvis 对子集图数据的 react

python - 我正在学习Python数据科学手册,并使用相同的代码得到了不同的图表。怎么了?

python - Pandas scatter_matrix - 绘制分类变量