首页 > 解决方案 > 尽管可以使用 .get_data() 检索数据,但 Matplotlib fig 未在图中显示更新的数据

问题描述

我想在我的绘图中与视频一起显示实时数据,并通过视频输出以供以后观察。正在遵循这个建议:Combining cv2.imshow() with matplotlib plt.show() in real time

# I have redacted a fair bit of the code for other subplots 
# as I am just working on getting the one to display but if 
# you would like to see the rest let me know. Did this for simplicity.

fig = plt.figure()
gs = gridspec.GridSpec(9,16)
gs.update(wspace=0, hspace=0, left=0.1, bottom=0.1)
ax2 = plt.subplot(gs[0:2,4:10])

speedArr = LapData["mSpeed"]*3.6 #Array of speed measured at time intervals
timeArr = LapData["mCurrentTime"] #Array of in-game lap time @ ^    ^

line1, = ax2.plot(timeArr, speedArr, "r")

print("Starting while loop to display video...")
x=0
telemetryLength = len(timeArr)
while cap.more():
    completionPerc = int(x/(vidLength/2)*len(timeArr))
    line1.set_data(np.array(timeArr[:completionPerc]),np.array(speedArr[:completionPerc]))
    fig.canvas.draw()
    print(line1.get_data())

    # convert canvas to image
    img = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='')
    img = img.reshape(fig.canvas.get_width_height()[::-1] + (3,))

    # img is rgb, convert to opencv's default bgr
    img = cv2.cvtColor(img,cv2.COLOR_RGB2BGR)

    # display image with opencv or any operation you like
    cv2.imshow("plot",img)    # The img does not display updated graph

print(line1.get_data()) 每次迭代都正确输出 x 和 y 数据集,如下所示:

(array([], dtype=float64), array([], dtype=float64))
(array([ 0.5]), array([ 68.31216]))
(array([ 0.5]), array([ 68.31216]))
(array([ 0.5     ,  0.586975]), array([ 68.31216,  69.23736]))
(array([ 0.5     ,  0.586975]), array([ 68.31216,  69.23736]))

但是图表继续不更新???

标签: pythonmatplotlib

解决方案


推荐阅读