5

I have a matplotlib window with multiple subplots in it. I want to be able to dynamically update the contents of each subplot whenever a method is called. The simplified code looks like this:

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 
7
  • 1
    So you mean to say that you want to update the subplots in a window that is already open? Commented Mar 24, 2016 at 10:52
  • Yes, that's exactly what I mean Commented Mar 24, 2016 at 10:53
  • @tom As in change the image that each subplot displays. In the example code, subplot 1 displays image1, I want to be able to change it so that subplot1 displays image2 for example when update_subplots() is called. Commented Mar 24, 2016 at 11:14
  • 1
    Can't you just do that with: ax_list[0].cla(); ax_list[0].imshow(image2), etc.? Commented Mar 24, 2016 at 11:18
  • The problem is that I want to do it from another method so ax_list won't be accessible, can't seem to find a getter method for it the documentation. Commented Mar 24, 2016 at 11:21

1 Answer 1

1

I've managed to figure out how to get this working- it's not very clean but it gets the job done.

We can set the figure to a global variable like so:

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

We can then modify the contents of the subplots from any method like so:

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() 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.