【问题标题】:matplotlib horizontal bar chart with time in hours:minutes:seconds on x axismatplotlib 水平条形图,时间以小时为单位:分钟:x 轴上的秒数
【发布时间】:2019-06-17 20:07:11
【问题描述】:

我想使用水平条形图显示用户在一天内花费在几项任务上的时间。 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()

我在某个地方找到了这个,但它不起作用。我什至无法对其进行调整以使其正常工作。请提出解决方案。此外,我还想显示每个水平条后花费的时间。对此的任何想法也是值得赞赏的。

【问题讨论】:

  • 您需要将字符串转换为秒或类似的格式,并使用自定义格式化程序来获取您喜欢的格式。或者,可以转换为日期时间,但这很容易出错,特别是如果需要错误栏。

标签: python matplotlib bar-chart


【解决方案1】:

根据重要的评论,我以秒为单位传递时间,并使用时间字符串显示为标签,它起作用了。

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')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多