Сохраните несколько фигур matplotlib в одном файле PDF с помощью Python
В этой статье мы обсудим, как сохранить несколько рисунков matplotlib в одном файле PDF с помощью Python. Мы можем использовать метод savefig() класса PdfPages для сохранения нескольких графиков в одном PDF-файле. Графики Matplotlib можно просто сохранить в виде файлов PDF с расширением .pdf. Это сохраняет рисунки, сгенерированные Matplotlib, в одном файле PDF с именем Сохранить несколько графиков как PDF.pdf в текущем рабочем каталоге.
Монтаж
pip install matplotlib
Пошаговая реализация
Чтобы найти решение, мы выполним несколько шагов.
Шаг 1: Импортируйте необходимые файлы.
Python3
from matplotlib import pyplot as pltfrom matplotlib.backends.backend_pdf import PdfPages |
Шаг 2: Установите размер фигуры и отрегулируйте отступы между подграфиками и вокруг них.
Python3
plt.rcParams["figure.figsize"] = [7.00, 3.50]plt.rcParams["figure.autolayout"] = True |
Шаг 3: Мы рассмотрим 3 графика, поэтому давайте назовем их fig1, fig2 и fig3, используя plt.figure().
Python3
fig1 = plt.figure()fig2 = plt.figure()Fig3 = plt.figure() |
Шаг 4: Постройте первую строку, используя метод plt.plot().
Python3
plt.plot([17, 45, 7, 8, 7], color="orange")plt.plot([13, 25, 1, 6, 3], color="blue")plt.plot([22, 11, 2, 1, 23], color="green") |
Шаг 5: Создайте функцию для сохранения нескольких изображений в файле PDF, скажем, save_image().
Python3
def save_image(filename): # PdfPages is a wrapper around pdf # file so there is no clash and # create files with no error. p = PdfPages(filename) # get_fignums Return list of existing # figure numbers fig_nums = plt.get_fignums() figs = [plt.figure(n) for n in fig_nums] # iterating over the numbers in list for fig in figs: # and saving the files fig.savefig(p, format="pdf") # close the object p.close() |
Полный код
Python3
import matplotlibfrom matplotlib import pyplot as pltfrom matplotlib.backends.backend_pdf import PdfPages # customizing runtime configuration stored# in matplotlib.rcParamsplt.rcParams["figure.figsize"] = [7.00, 3.50]plt.rcParams["figure.autolayout"] = True fig1 = plt.figure()plt.plot([17, 45, 7, 8, 7], color="orange") fig2 = plt.figure()plt.plot([13, 25, 1, 6, 3], color="blue") Fig3 = plt.figure()plt.plot([22, 11, 2, 1, 23], color="green") def save_image(filename): # PdfPages is a wrapper around pdf # file so there is no clash and create # files with no error. p = PdfPages(filename) # get_fignums Return list of existing # figure numbers fig_nums = plt.get_fignums() figs = [plt.figure(n) for n in fig_nums] # iterating over the numbers in list for fig in figs: # and saving the files fig.savefig(p, format="pdf") # close the object p.close() # name your Pdf filefilename = "multi_plot_image.pdf" # call the functionsave_image(filename) |
Выход:
Теперь, после запуска кода, вы можете увидеть в своем локальном каталоге, что PDF-файл, содержащий все три графика, будет сохранен в формате PDF с именем «multi_plot_image.pdf».


