python - 如何让 matplotlib (pyplot) 绘图循环更新?

标签 python matplotlib

我读过很多类似的帖子,但没有任何效果。我有一个循环,正在尝试更新 3 个包含带有文本叠加图像的数字,有点像这样:

def updatePlot(data, fig):
  fig.clear()
  ax = fig.subplots()
  ax.imshow(...)
  ax.text(...)
  plt.show()
  plt.draw()
  plt.pause(0.0001)

fig1 = plt.figure()
fig2 = plt.figure()
fig3 = plt.figure()

while True:
  # do computation
  updatePlot(..., fig1)
  updatePlot(..., fig2)
  updatePlot(..., fig3)

症状是只有Fig3更新,其他保持静态,直到我杀死程序,然后它们刷新。我正在 ipython 终端(在 Spyder 中)工作。

最佳答案

以下内容应该有效。它以交互模式 (plt.ion()) 运行并刷新每个图窗上的事件。

import numpy as np
import matplotlib.pyplot as plt

plt.ion()

def updatePlot(data, fig):
  fig.clear()
  ax = fig.subplots()
  ax.imshow(data)
  ax.text(2,2, np.mean(data))

  plt.pause(0.1)
  fig.canvas.draw_idle()
  fig.canvas.flush_events()

fig1 = plt.figure()
fig2 = plt.figure()
fig3 = plt.figure()

while True:
  # do computation
  updatePlot(np.random.rand(4,4), fig1)
  updatePlot(np.random.rand(6,6), fig2)
  updatePlot(np.random.rand(10,10), fig3)

但这非常不稳定且效率低下。也许可以考虑使用FuncAnimation

import numpy as np
import matplotlib.animation
import matplotlib.pyplot as plt


def updatePlot(data, image, text):
    image.set_data(data)
    text.set_text(data.mean())

fig1, ax1 = plt.subplots()
image1 = ax1.imshow(np.random.rand(4,4))
text1 = ax1.text(2,2, "")

fig2, ax2 = plt.subplots()
image2 = ax2.imshow(np.random.rand(6,6))
text2 = ax2.text(2,2, "")

fig3, ax3 = plt.subplots()
text3 = ax3.text(2,2, "")
image3 = ax3.imshow(np.random.rand(10,10))

def update_plots(i):
    # do computation
    updatePlot(np.random.rand(4,4), image1, text1)
    updatePlot(np.random.rand(6,6), image2, text2)
    updatePlot(np.random.rand(10,10), image3, text3)
    fig2.canvas.draw_idle()
    fig3.canvas.draw_idle()

ani = matplotlib.animation.FuncAnimation(fig1, update_plots, interval=40)

plt.show()

关于python - 如何让 matplotlib (pyplot) 绘图循环更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55660592/

相关文章:

python - subprocess.Popen 的管道输出到文件

python - plt.imshow() 的单色图像显示为黑色

python - 在 map 上绘制点,但错误代码为 "ValueError: ' box_aspect' 且 'fig_aspect' 必须为正值"

python - 面向对象访问matplotlib中的fill_between阴影区域

javascript - Python - 单击一个 javascript 按钮

python - __iter__ 返回迭代器对象本身的目的是什么?

python - Pandas :使用元组索引将数据从两个数据帧移动到另一个数据帧

python - 获取组名称作为图形 matplotlib 中的轴

python - 在 matplotlib 中组合多个热图

python - 在一个循环中分配增量文件名