Python matplotlib set_array()只接受2个参数(给定3个)

2024-06-02 22:42:32 发布

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

我正在尝试设置一个动画,以实时显示通过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个参数?我不明白,因为我只能看到两个论点。 我怎样才能纠正这个错误呢?

编辑:我应该注意,显示的代码并不完整,只是有错误的部分,为了清楚起见,删除了其他部分。


Tags: 数据函数newdata参数matplotlibdef错误
1条回答
网友
1楼 · 发布于 2024-06-02 22:42:32

我觉得你在一些事情上有点困惑。

  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') 

相关问题 更多 >