T Xu
T Xu

Reputation: 13

Jupyter Notebook Save Multiple Plots As One PDF

Say I have multiple images/plots produced by seaborn or matplotlib in a Python Jupyter Notebook. How do I save all of them into one PDF file in one go?

Upvotes: 1

Views: 3131

Answers (3)

Pavlenty
Pavlenty

Reputation: 13

You can use PdfPages from matplotlib:

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

pp = PdfPages('test.pdf')
plt.figure()
plt.plot(np.arange(10))
pp.savefig()
plt.figure()
plt.plot(np.arange(10)**2)
pp.savefig()
pp.close()

Upvotes: 0

George
George

Reputation: 140

For matplotlib you can create subplots inside the same figureand use plt.savefig to save as PDF or PNG. Based on this documentation you can:

import matplotlib.pyplot as plt
import numpy as np

# Some example data to display
x = np.linspace(0, 2 * np.pi, 400)
y = np.sin(x ** 2)

fig, axs = plt.subplots(2, 2, figsize=(30, 15))
axs[0, 0].plot(x, y)
axs[0, 0].set_title('Axis [0, 0]', fontsize = 20)
axs[0, 0].set_xlabel('x-label for [0,0] plot', fontsize=18)
axs[0, 0].set_ylabel('y-label for [0,0] plot', fontsize=18)

axs[0, 1].plot(-x, y, 'tab:orange')
axs[0, 1].set_title('Axis [0, 1]', fontsize = 20)
axs[1, 0].plot(x, -y, 'tab:green')
axs[1, 0].set_title('Axis [1, 0]', fontsize = 20)
axs[1, 1].plot(x, 2*y, 'tab:red')
axs[1, 1].set_title('Axis [1, 1]', fontsize = 20)

# .pdf for your case, default .png
plt.savefig(r'yourpath\fig1.pdf', bbox_inches='tight', dpi=300)

Rearrange your plots how you like and set figsize and fontsize to make the output PDF readable. Here you'd have this downloaded as single-paged PDF: enter image description here

Check here for sns.subplot and use savefig again.

If you want to save figures created in different cells inside your notebook (in seperate PDF pages) try something like this:

fig1= plt.figure(...)
plt.plot(...)
fig2= plt.figure(...)
plt.plot(...)
from matplotlib.backends.backend_pdf import PdfPages
def multiple_figues(filename):
    pp = PdfPages(filename)
    fig_nums = plt.get_fignums()
    figs = [plt.figure(n) for n in fig_nums]
    for fig in figs:
        fig.savefig(pp, format='pdf')
    pp.close()

Upvotes: 1

Fateme Pasandide
Fateme Pasandide

Reputation: 51

in notebook : file => Download as => PDF ...

or

you can import your file in google drive, and open it with google colab then : file => print => save it as a pdf.

Upvotes: 1

Related Questions