我正在尝试绘制两个更新图,一个是图表,另一个是从相机捕获的图像。
我在这一行收到错误:
"current_line.set_data(y_data)" in the "update" function.
The error says: "AttributeError: 'list' object has no attribute 'set_data'".
我知道为什么会收到此错误?如果我注释掉这一行,我将从相机中更改图像,除了第二个绘图之外的所有内容似乎都很好(因为第二个绘图没有更新)但我需要更新第二个绘图。
y_data = [0]
# Capture intial frame
ret, initial_frame = lsd.cap.read()
# Function for making the initial figure
def makeFigure():
fig = plt.figure()
# Show frame
ax1 = plt.subplot2grid((2, 2), (0, 0), colspan=2)
plot_frame = ax1.imshow(initial_frame, animated=True)
# Set the limits of the plot and plot the graph
ax2 = plt.subplot2grid((2, 2), (1, 0), colspan=2)
ax2.set_title('Title')
ax2.set_ylabel('Y-Label')
ax2.set_ylim(0, 100)
ax2.set_xlim(0, 100)
ax2.grid()
line = ax2.plot(y_data, 'o-')
return fig, plot_frame, line
def update(i, current_frame, current_line, y_data):
# Capture original frame_new_RGB from camera
ret, frame_new_original = lsd.cap.read()
# Changing frame_new_original's color order
frame_new_RGB = cv2.cvtColor(frame_new_original, cv2.COLOR_BGRA2RGB)
y_data.append(randint(0, 9))
# Update figure
current_line.set_data(y_data)
# Update frame
current_frame.set_data(frame_new_RGB)
# Make figures and animate the figures
curr_fig, curr_frame, curr_line = makeFigure()
anim = FuncAnimation(curr_fig, update, fargs=[curr_frame, curr_line, y_data], interval=10)
plt.show()
# When everything done, release the capture
lsd.cap.release()
cv2.destroyAllWindows()
更新后的问题:
第一个问题已经解决,但现在我面临另一个问题。我的程序在运行之后冻结并且它不会产生任何错误。还有一件事可能与这个问题有关,我是多线程的,这段代码在主线程中。
答案 0 :(得分:1)
ax.plot
返回Line2D
个实例的列表(在您的情况下,它是一个1项列表)。这是因为可以使用ax.plot
一次性绘制多条线。
因此,在您的情况下,您只需要抓住列表的第一项。最简单的方法可能是改变这一行:
line = ax2.plot(y_data, 'o-')
到此:
line, = ax2.plot(y_data, 'o-')
请注意,虽然您的问题是关于设置该行的data
,而不是添加legend
,但此Q& A与此相关,因为解决方案是相同的:{{3} }