matplotlib水平条形图,时间沿x轴以小时:分钟:秒为单位

时间:2019-06-17 20:07:11

标签: python matplotlib bar-chart

我想使用水平条形图显示用户一天中花费多少时间完成几个任务。 y轴是任务列表,x轴是在这些任务上花费的时间。时间采用%H:%M:%S格式。

fig, ax = plt.subplots()

# Example data
tasks = ('Reading', 'Mobile', 'Outing', 'Laptop')
y_pos = np.arange(len(tasks))
time_spent = ["01:01:34","00:05:23","00:00:09","02:34:32"]
error = np.random.rand(len(tasks))

ax.barh(y_pos, time_spent, xerr=error, align='center')
ax.set_yticks(y_pos)
ax.set_yticklabels(tasks)
ax.set_xlabel('Time spent')
ax.xaxis.set_major_locator(HourLocator())
ax.xaxis.set_major_formatter(DateFormatter('%H:%M:%S'))

plt.show()

我在某个地方找到了它,但是它不起作用。我什至无法调整它来工作。请提出解决方案。此外,我还想显示每个单杠之后花费的时间。对此的任何想法也是可以理解的。

1 个答案:

答案 0 :(得分:0)

根据最重要的评论的重要性,我以秒为单位传递时间,并使用时间字符串显示为标签并且有效。

fig, ax = plt.subplots()

# Example data
tasks = ('Reading', 'Mobile', 'Outing', 'Laptop')
time_spent = ["01:01:34","00:05:23","00:00:09","02:34:32"]
timesec = []
for i in range(4):
    timesec.append(convertToSeconds(time_spent[i]))
y_pos = np.arange(len(tasks))
error = np.random.rand(len(tasks))

ax.barh(y_pos, timesec, xerr=error, align='center')
ax.set_yticks(y_pos)
ax.set_yticklabels(tasks)
ax.set_xlabel('Time Spent')
ax.get_xaxis().set_visible(False)

for i, v in enumerate(times):
    print(i)
    ax.text(v + 3, i, time_spent[i], color='blue')
相关问题