buhtz
buhtz

Reputation: 12202

Use datetime.date in matplotlib with Python3

I try to plot tuple-values. There is one float for each day. I tried this:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import matplotlib.pyplot as plt
import datetime

d = tuple()
d += (70.3, datetime.date(2015, 1, 7))
d += (60.1, datetime.date(2015, 2, 5))
d += (68.8, datetime.date(2015, 6, 2))

plt.plot(d)
plt.show()

This doesn't work because of

> Traceback (most recent call last):   File "./m.py", line 12, in
> <module>
>     plt.plot(d)   File "/usr/local/lib/python3.4/dist-packages/matplotlib-1.5.dev1-py3.4-linux-i686.egg/matplotlib/pyplot.py",
> line 3129, in plot
>     ret = ax.plot(*args, **kwargs)   File "/usr/local/lib/python3.4/dist-packages/matplotlib-1.5.dev1-py3.4-linux-i686.egg/matplotlib/axes/_axes.py",
> line 1382, in plot
>     self.add_line(line)   File "/usr/local/lib/python3.4/dist-packages/matplotlib-1.5.dev1-py3.4-linux-i686.egg/matplotlib/axes/_base.py",
> line 1568, in add_line
>     self._update_line_limits(line)   File "/usr/local/lib/python3.4/dist-packages/matplotlib-1.5.dev1-py3.4-linux-i686.egg/matplotlib/axes/_base.py",
> line 1579, in _update_line_limits
>     path = line.get_path()   File "/usr/local/lib/python3.4/dist-packages/matplotlib-1.5.dev1-py3.4-linux-i686.egg/matplotlib/lines.py",
> line 908, in get_path
>     self.recache()   File "/usr/local/lib/python3.4/dist-packages/matplotlib-1.5.dev1-py3.4-linux-i686.egg/matplotlib/lines.py",
> line 609, in recache
>     y = np.asarray(yconv, np.float_)   File "/usr/local/lib/python3.4/dist-packages/numpy/core/numeric.py", line
> 462, in asarray
>     return array(a, dtype, copy=False, order=order) TypeError: float() argument must be a string or a number, not 'datetime.datetime'

But looking into the matplotlib docu datetime should be full supported.

Upvotes: 0

Views: 374

Answers (1)

Amy Teegarden
Amy Teegarden

Reputation: 3972

Try listing all of the floats together and all of the dates together:

import matplotlib.pyplot as plt
import datetime
dates = [datetime.date(2015, 1, 7), datetime.date(2015, 2, 5), datetime.date(2015, 6, 2)]
Y = [70.3, 60.1, 68.8]
plt.plot(dates, Y)
plt.show()

Upvotes: 2

Related Questions