使用matplotlib和python绘制datetime.timedelta [英] Plot datetime.timedelta using matplotlib and python
问题描述
我正在执行一项任务,我需要计算每天花费的时间,然后使用条形图表示该时间,因此对于此任务,我使用python并能够获取每天花费的时间,并将其存储在列表"time_list"中,现在我不明白如何使用matplotlib函数对此进行绘制. 问题在于,此列表包含datetime.timedelta类值. 示例:
I am working on a task, where I need to calculate time spent on each day and then represent that time using a bar plot, so for this task I used python and able to get time spent on each day, and stored it in a list "time_list", now I don't understand how to plot this using matplotlib function. The problem is that, this list contains datetime.timedelta class values. Example:
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
有人可以帮我作图吗? 预先感谢
Can someone help me in plotting this. Thanks in advance
推荐答案
虽然matplotlib原则上可以处理日期时间对象,但条形图无法直接解释它们.因此,可以在时间增量上添加任意日期,然后使用matplotlib.dates.date2num()
转换为数字.然后使用DateFormatter
启用漂亮的刻度标签.
While matplotlib can in principle handle datetime objects, the bar plot cannot interprete them directly. So one may add an arbitrary date to the timedeltas and convert to numbers using matplotlib.dates.date2num()
. Then using a DateFormatter
enables nice ticklabels.
import numpy as np
import datetime
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
days = [2, 3, 4, 5, 8, 9, 10, 11, 12, 15, 16]
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)]
# specify a date to use for the times
zero = datetime.datetime(2018,1,1)
time = [zero + t for t in time_list]
# convert datetimes to numbers
zero = mdates.date2num(zero)
time = [t-zero for t in mdates.date2num(time)]
f = plt.figure()
ax = f.add_subplot(1,1,1)
ax.bar(days, time, bottom=zero)
ax.yaxis_date()
ax.yaxis.set_major_formatter(mdates.DateFormatter("%H:%M"))
# add 10% margin on top (since ax.margins seems to not work here)
ylim = ax.get_ylim()
ax.set_ylim(None, ylim[1]+0.1*np.diff(ylim))
plt.show()
这篇关于使用matplotlib和python绘制datetime.timedelta的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!