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

4

我有一个matplotlib窗口,其中包含多个子图。我希望能够在调用方法时动态更新每个子图的内容。简化的代码如下:

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

1
所以你的意思是说你想要更新已经打开的窗口中的子图? - Srivatsan
是的,那正是我所指的。 - user3396592
@tom,就是更改每个子图显示的图像。在示例代码中,子图1显示image1,我想能够更改它,以便在调用update_subplots()时,子图1显示例如image2。 - user3396592
1
你不能只用这个吗:ax_list[0].cla(); ax_list[0].imshow(image2),等等? - tmdavison
def update_subplot(subplot): - gboffi
显示剩余2条评论
1个回答

1
我已经成功地弄清楚了如何让这个工作-它并不是非常干净,但它完成了任务。
我们可以像这样将图形设置为全局变量:
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()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接