0

I want to show how much time a user spends on few tasks in a day using horizontal bar chart. y-axis is list of tasks and x-axis is time spent on those tasks. The time is in %H:%M:%S format.

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

I found this somewhere and it's not working. I am not even able to tweak it to get worked. Please suggest the solution. Additionally, I also want to show the time spent after each horizontal bar. Any ideas for that are also appreciable.

Shashwat Kumar
  • 5,159
  • 2
  • 30
  • 66
  • You will need to convert your strings to seconds or similar and use a custom formatter for getting the format you like. Alternatively, one could convert to datetime, but that would be errorprone, especialy if then wanting errorbars. – ImportanceOfBeingErnest Jun 17 '19 at 20:16

1 Answers1

0

As per importanceofbeingernest comment, I passed time in seconds and used the time string to show as label and it worked.

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')
Shashwat Kumar
  • 5,159
  • 2
  • 30
  • 66