Python matplotlib set_array()方法需要2个参数,但给出了3个参数。

11

我试图设置一个动画来实时显示通过GPIB接口获取的一些数据。只要我使用线,也就是matplotlib的plot()函数,我就可以很好地工作。

然而,由于我正在获取离散数据点,所以我想使用scatter()函数。这导致了以下错误:“set_array()需要正好2个参数(给出3个)”

下面的代码中显示了错误在2个位置上的表现。

def intitalisation():
    realtime_data.set_array([0],[0])     ******ERROR HERE*******
    return realtime_data,


def update(current_x_data,new_xdata,current_y_data, new_ydata):#

    current_x_data = numpy.append(current_x_data, new_xdata)
    current_y_data =  numpy.append(current_y_data, new_ydata)

    realtime_data.set_array( current_x_data  , current_y_data  )      ******ERROR HERE*******


def animate(i,current_x_data,current_y_data):

    update(current_x_data,new_time,current_y_data,averaged_voltage)
    return realtime_data,


animation = animation.FuncAnimation(figure, animate, init_func=intitalisation, frames = number_of_measurements, interval=time_between_measurements*60*1000, blit=False, fargs= (current_x_data,current_y_data))

figure = matplotlib.pyplot.figure()


axes = matplotlib.pyplot.axes()

realtime_data = matplotlib.pyplot.scatter([],[]) 

matplotlib.pyplot.show()

那么我对大家的问题是,为什么set_array()认为我向它传递了3个参数?我不理解,因为我只看到有2个参数。

另外,我该如何纠正这个错误?

1个回答

12

我认为你对几件事情有些困惑。

  1. 如果你想改变x和y的位置,那么你使用的方法是错误的。`set_array`控制颜色数组。对于`scatter`返回的集合,您可以使用`set_offsets`来控制x和y的位置。(使用哪种方法取决于涉及的图形类型。)
  2. 两个参数与三个参数之间的区别在于,`artist.set_array`是对象的一个方法,因此第一个参数是所涉及的对象。

为了解释第一点,这里有一个简单的动画示例:

import matplotlib.pyplot as plt
import numpy as np

x, y, z = np.random.random((3, 100))

plt.ion()

fig, ax = plt.subplots()
scat = ax.scatter(x, y, c=z, s=200)

for _ in range(20):
    # Change the colors...
    scat.set_array(np.random.random(100))
    # Change the x,y positions. This expects a _single_ 2xN, 2D array
    scat.set_offsets(np.random.random((2,100)))
    fig.canvas.draw()

要解释第二点,在Python中定义类时,第一个参数是该类的实例(通常称为self)。每当调用对象的方法时,这个参数都会在幕后传递进去。
例如:
class Foo:
    def __init__(self):
        self.x = 'Hi'

    def sayhi(self, something):
        print self.x, something

f = Foo() # Note that we didn't define an argument, but `self` will be passed in
f.sayhi('blah') # This will print "Hi blah"

# This will raise: TypeError: bar() takes exactly 2 arguments (3 given)
f.sayhi('foo', 'bar') 

谢谢Joe,这对让我的代码工作起来非常有帮助。 虽然我实际上不能使用set_offsets,但我已经查看了它的文档,我就是不明白如何将x和y数据发送到它。 就理解而言,老实说,我从来没有理解过类是什么以及它们的用途,所以将类的实例作为参数传递给自身的概念并没有任何意义。所以感谢您的帮助,但我想我要放弃我在这里尝试做的事情。 - user3389255
如果你有x和y的序列,只需传入类似这样的内容:artist.set_offsets([[x0, x1, ...], [y0, y1, ...]])。它将被转换为一个2D numpy数组。在你的示例代码中,可能是realtime_data.set_offsets([current_x_data , current_y_data]) - Joe Kington
好的。那么我现在面临的问题是如何改变坐标轴。因为当动画重新绘制时,坐标轴不会自动更新。 即使在动画函数中设置blit=False,它仍然不会重新绘制。 - user3389255
shape(offsets) = (4097, 2)shape(alpha) = (4097,)s.set_offsets(offsets) 看起来可以工作,但是在 makeMappingArray 中 s.set_array(alpha) 会产生 IndexError: tuple index out of range。如果 len(shape) != 2 and shape[1] != 3:,我不知道这意味着什么。当我尝试您的示例和一个4元素数组时,它能够工作... - endolith

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接