Why do I get an AttributeError when I use scatter() but not when I use plot()

sbhatla picture sbhatla · Jun 20, 2014 · Viewed 7.8k times · Source

I wish to plot using Matplotlib/pylab and show date and time on the x-axis. For this, I'm using the datetime module.

Here is a working code that does exactly what is required-

import datetime
from pylab import *

figure()
t2=[]
t2.append(datetime.datetime(1970,1,1))
t2.append(datetime.datetime(2000,1,1))
xend= datetime.datetime.now()
yy=['0', '1']
plot(t2, yy)
print "lim is", xend
xlim(datetime.datetime(1980,1,1), xend)

However, when I use the scatter(t2,yy) command instead of plot (t2,yy), it gives an error:

AttributeError: 'numpy.string_' object has no attribute 'toordinal'

Why is this happening and how can I show a scatter along with plot?

A similar question has been asked before as- AttributeError: 'time.struct_time' object has no attribute 'toordinal' but the solutions don't help.

Answer

Paul H picture Paul H · Jun 20, 2014

Here's an extended example of how I would do this:

import datetime
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
t2=[
    datetime.datetime(1970,1,1),
    datetime.datetime(2000,1,1)
]
xend = datetime.datetime.now()
yy= [0, 1]
ax.plot(t2, yy, linestyle='none', marker='s', 
        markerfacecolor='cornflowerblue', 
        markeredgecolor='black',
        markersize=7,
        label='my scatter plot')

print("lim is {0}".format(xend))
ax.set_xlim(left=datetime.datetime(1960,1,1), right=xend)
ax.set_ylim(bottom=-1, top=2)
ax.set_xlabel('Date')
ax.set_ylabel('Value')
ax.legend(loc='upper left')

enter image description here