Python matplotlib set_array() 需要两个参数(给了三个)
我正在尝试设置一个动画,实时显示通过GPIB接口获取的一些数据。只要我使用直线,也就是matplotlib的plot()函数,这个动画就能正常工作。
但是,由于我获取的是离散的数据点,我想使用scatter()函数来显示这些点。结果我遇到了一个错误:
“set_array()需要两个参数,但我给了它三个。”
这个错误在下面代码中的两个地方出现了。
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()会认为我给了它三个参数呢?我只看到两个参数,不明白为什么会这样。还有,我该如何修正这个错误呢?
补充说明:我想说的是,显示的代码并不完整,只是包含了错误的那部分,其他部分为了清晰起见被删掉了。
1 个回答
12
我觉得你在几个方面有点混淆。
- 如果你想改变 x 和 y 的位置,你用错了方法。
set_array
是用来控制 颜色 数组的。对于scatter
返回的集合,你应该使用set_offsets
来控制 x 和 y 的位置。(你用哪个方法取决于你在处理的对象类型。) - 关于两个参数和三个参数的问题,是因为
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')