为什么我在使用scatter()时会出现AttributeError,而使用plot()时却不会
我想用Matplotlib/pylab来绘制图表,并在x轴
上显示日期和时间。为此,我使用了datetime模块。
下面是一个可以正常工作的代码,正好满足我的需求-
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)
但是,当我用scatter(t2,yy)
这个命令代替plot(t2,yy)
时,出现了一个错误:
AttributeError: 'numpy.string_' object has no attribute 'toordinal'
这是什么原因呢?我该如何同时显示散点图和折线图呢?
之前也有人问过类似的问题,链接是- AttributeError: 'time.struct_time' object has no attribute 'toordinal' 但那些解决方案对我没有帮助。
2 个回答
2
下面是一个更详细的例子,展示我会如何做到这一点:
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')
0
如果你把 yy
设置成 int
(整数)或者 float
(浮点数)类型的话,就不会在使用 scatter()
时遇到这个错误了:
yy = [0, 1]