更新已打开的 Matplotlib 图中的子图

Update subplots in Matplotlib figure that is already open

我有一个 matplotlib window,里面有多个子图。我希望能够在调用方法时动态更新每个子图的内容。简化的代码如下所示:

import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure(1)
fig, ax_list = plt.subplots(3, 2)

image1 = plt.imread("image1.jpg")
image2 = plt.imread("image2.jpg")
ax_list = ax_list.ravel()
ax_list[0].imshow(image1)
ax_list[1].imshow(image2)
plt.show()

def update_subplots():
  # I want this method to change the contents of the subplots whenever it is called
  pass

我已经设法弄清楚如何让它工作 - 它不是很干净,但它完成了工作。

我们可以像这样将图形设置为全局变量:

fig, ax_list = plt.subplots(4, 2)

然后我们可以通过任何方法修改子图的内容,如下所示:

def update_subplot(image):
  global fig, ax_list
  ax_list = ax_list.ravel()
  # ax_list[0] refers to the first subplot
  ax_list[0].imshow(image)
  plt.draw()