3

I have list of timestamps in the format of HH:MM:SS and want to plot against some values using datetime.time. Seems like python doesn't like the way I do it. Can someone please help ?

import datetime
import matplotlib.pyplot as plt

# random data
x = [datetime.time(12,10,10), datetime.time(12, 11, 10)]
y = [1,5]

# plot
plt.plot(x,y)
plt.show()

*TypeError: float() argument must be a string or a number*
cel
  • 27,769
  • 16
  • 88
  • 113
maulik mehta
  • 175
  • 1
  • 3
  • 10

2 Answers2

2

Well, a two-step story to get 'em PLOT really nice

enter image description here

Step 1: prepare data into a proper format

from a datetime to a matplotlib convention compatible float for dates/times


As usual, devil is hidden in detail.

matplotlib dates are almost equal, but not equal:

#  mPlotDATEs.date2num.__doc__
#                  
#     *d* is either a class `datetime` instance or a sequence of datetimes.
#
#     Return value is a floating point number (or sequence of floats)
#     which gives the number of days (fraction part represents hours,
#     minutes, seconds) since 0001-01-01 00:00:00 UTC, *plus* *one*.
#     The addition of one here is a historical artifact.  Also, note
#     that the Gregorian calendar is assumed; this is not universal
#     practice.  For details, see the module docstring.

So, highly recommended to re-use their "own" tool:

from matplotlib import dates as mPlotDATEs   # helper functions num2date()
#                                            #              and date2num()
#                                            #              to convert to/from.

Step 2: manage axis-labels & formatting & scale (min/max) as a next issue

matplotlib brings you arms for this part too.

Check code in this answer for all details

Community
  • 1
  • 1
user3666197
  • 1
  • 6
  • 45
  • 89
2

It is still valid issue in Python 3.5.3 and Matplotlib 2.1.0.

A workaround is to use datetime.datetime objects instead of datetime.time ones:

import datetime
import matplotlib.pyplot as plt

# random data
x = [datetime.time(12,10,10), datetime.time(12, 11, 10)]
x_dt = [datetime.datetime.combine(datetime.date.today(), t) for t in x]
y = [1,5]

# plot
plt.plot(x_dt, y)
plt.show()

enter image description here

By deafult date part should not be visible. Otherwise you can always use DateFormatter:

import matplotlib.dates as mdates
ax.xaxis.set_major_formatter(mdates.DateFormatter('%H-%M-%S'))
michal.dul
  • 135
  • 1
  • 2
  • 9