【问题标题】:Why do I get an AttributeError when I use scatter() but not when I use plot()为什么我在使用 scatter() 时会收到 AttributeError,但在使用 plot() 时却没有
【发布时间】:2014-06-19 22:44:17
【问题描述】:

我希望使用 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_' 对象没有属性 'toordinal'

为什么会发生这种情况?如何在情节中显示散点图?

之前有人问过一个类似的问题- AttributeError: 'time.struct_time' object has no attribute 'toordinal' 但解决方案无济于事。

【问题讨论】:

  • 您希望用scatter 完成哪些plot 无法处理的任务?我从概念上问 b/c,我认为 scatter 不适合时间序列——但即使在我自己看来,这也是一个相当随意的区别。
  • 'plot' 向我展示了一条连接所有数据点的线,但不是数据点本身(除非有一种我不知道的方法)。但我还想显示数据点,以便查看者知道收集数据的时间点。
  • 在不相关的注释中,如何在堆栈溢出中显示内联代码?就像您在上面使用 scatter 和 plot 所做的那样。
  • 第一个问题,plot(x, y, 'ko'),你只会得到黑点。第二,使用反引号:“`”

标签: python matplotlib python-datetime


【解决方案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')

【讨论】:

    【解决方案2】:

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

    yy = [0, 1]
    

    【讨论】:

      猜你喜欢
      • 2023-03-14
      • 2017-04-24
      • 1970-01-01
      • 1970-01-01
      • 2016-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多