我正在执行一项任务,我需要计算每天花费的时间,然后使用条形图表示该时间。因此,对于此任务,我使用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上添加任意日期,然后使用转换为数字matplotlib.dates.date2num()。然后使用DateFormatter启用漂亮的ticklabels。
matplotlib.dates.date2num()
DateFormatter
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()