Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 521
sbhatla Avatar asked Jun 19 '14 22:06

sbhatla


People also ask

What are the 2 arguments passed in the scatter plot function?

The required positional arguments supplied to ax. scatter() are two lists or arrays. The first positional argument specifies the x-value of each point on the scatter plot. The second positional argument specifies the y-value of each point on the scatter plot.

What does PLT scatter do?

scatter() Scatter plots are used to observe relationship between variables and uses dots to represent the relationship between them. The scatter() method in the matplotlib library is used to draw a scatter plot.


1 Answers

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

like image 167
Paul H Avatar answered Oct 14 '22 08:10

Paul H