为什么在使用scatter()而不是plot()时获得attributeRor

2024-09-30 06:33:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望使用Matplotlib/pylab绘制,并在x-axis上显示日期和时间。为此,我使用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' 但解决办法没有帮助。


Tags: noimportdatetimeobjecttimeplotattributeattributeerror
2条回答

如果对yy使用intfloat类型,则在使用scatter()时不会出现此错误:

yy = [0, 1]

下面是一个扩展示例,说明我将如何执行此操作:

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

相关问题 更多 >

    热门问题