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

标签 python animation matplotlib

我正在尝试设置一个动画来显示实时通过 GPIB 接口(interface)获取的一些数据。只要我使用一条线,即 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. 如果您尝试随机计算 x 和 y 位置,则说明您使用了错误的方法。 set_array 控制color 数组。对于 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') 

关于Python matplotlib set_array() 正好接受 2 个参数(给定 3 个),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22254776/

相关文章:

javascript - 使用 javascript setInterval 函数,一个 div 启动内容到 fadeToggle,另一个 div 停止 fadeToggle 动画

ios - UIView水平动画不水平

python - 更改 Path PosixPath 对象中的文件名前缀

python - SVC sklearn 的 gamma 默认值

javascript - 使用javascript移动元素

python - Matplotlib.动画 : how to remove white margin

python - 在 BeautifulSoup 中索引多个表

python - Matplotlib 绘图具有更精细的刻度线,但没有标签

python - 调用列表上的函数

python - 将两个 Pandas 数据帧与仅添加整数计数相结合