chubaz
chubaz

Reputation: 53

How to create a function that outputs a matplotlib figure?

My aim is to create a function that outputs a figure.

If I try to call my function multiple times in a script, it only shows the figure from the first call. Only once I close the first figure, that the program creates the second and so on and so forth.

my function roughly looks like this:

def graphs(...,fig):
...
ax = plt.figure(fig)
...
...
plt.show

For the moment the function doesn't return anything, is there a way I could output the graph or at least make it so that it doesn't stop creating figures after the first one?

Upvotes: 5

Views: 2923

Answers (1)

Sudeep Juvekar
Sudeep Juvekar

Reputation: 5068

Use plt.figure().canvas.draw(). Check this thread: How to update a plot in matplotlib?

Your method then becomes

def graphs(..., fig):
    ax = plt.figure(fig)
    plt.figure().canvas.draw()

Finally, call plt.show() at the end of your loop

for ...:
  graphs(...., arg)
plt.show()

This will plot all figures in multiple windows. Beware that it will create one window per figure. Use subplots if you have huge number of images

Upvotes: 2

Related Questions