Seba Ma
Seba Ma

Reputation: 13

Saving a plot from multiple subplots

%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
fig,ax=plt.subplots(2,2,figsize=(15,10))
x=np.linspace(-3,3)
ax[0,0].plot(x,foo-function)

now I need a way to save each of the 4 plots into one file like this:

plt1=topleft_plot.saveNOTfigBUTplot('quadfunction.pdf')

how?

Upvotes: 1

Views: 3315

Answers (1)

FlapJack
FlapJack

Reputation: 156

Using the answer here: https://stackoverflow.com/a/4328608/16299117

We can do the following to save a SINGLE subplot from the overall figure:

import matplotlib.pyplot as plt
import numpy as np

fig,ax=plt.subplots(2,2,figsize=(15,10))

x=np.linspace(-3,3)

ax[0,0].plot(x,x**2) # This is just to make an actual plot.

# I am not using jupyter notebook, so I use this to show it instead of %inline
plt.show()

# Getting only the axes specified by ax[0,0]
extent = ax[0,0].get_window_extent().transformed(fig.dpi_scale_trans.inverted())

# Saving it to a pdf file. 
fig.savefig('ax2_figure.pdf', bbox_inches=extent.expanded(1.1, 1.2))

EDIT: I believe I may have misunderstood what you want. If you want to save EACH plot individually, say as 4 different pages in a pdf, you can do the following adapted from this answer: https://stackoverflow.com/a/29435953/16299117

This will save each subplot from the figure as a different page in a single pdf.

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.backends.backend_pdf import PdfPages

fig,ax=plt.subplots(2,2,figsize=(15,10))

x=np.linspace(-3,3)

ax[0,0].plot(x,x**2) # This is just to make an actual plot.


with PdfPages('foo.pdf') as pdf:
   for x in range(ax.shape[0]):
       for y in range(ax.shape[1]):
           extent = ax[x, y].get_window_extent().transformed(fig.dpi_scale_trans.inverted())
           pdf.savefig(bbox_inches=extent.expanded(1.1, 1.2))

Upvotes: 2

Related Questions