Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Activate a figure in matplotlib

It seems easy but I could not find any solution for opening multiple figures and save them by their name. I look for something like this:

fig1, ax1 = pl.subplots(1)
fig2, ax2 = pl.subplots(1)
...
pl.savefig('f1.png', fig1)
pl.savefig('f2.png', fig2)

usually pl.savefig acts on the last active figure. So how one can activate a figure and save it, then repeat the process for the rest of the figures?

like image 707
Abolfazl Avatar asked Apr 08 '26 16:04

Abolfazl


1 Answers

You can save an image using the figure object itself:

fig1.savefig(...)

Alternatively, you can change the current figure by calling plt.figure(1) to select the first figure that was create and then use plt.savefig(). Or, you can use plt.figure(fig1.number) to switch focus to fig1

import matplotlib.pyplot as plt

fig1, ax1 = plt.subplots(1)
fig2, ax2 = plt.subplots(1)

# Can choose one of the below to change the current figure
plt.figure(1)
# plt.figure(fig1.number)

plt.savefig(...) # will save fig1
like image 88
DavidG Avatar answered Apr 10 '26 07:04

DavidG



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!