21
20

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

matplotlibで複数のfigureを一つのpdfに保存する

Posted at

内容

タイトル通りですが、複数のfigureをまとめて一つのpdfに保存するやり方です。

やり方

from matplotlib.backends.backend_pdf import PdfPages

# ファイルを開く
pdf = PdfPages('test.pdf')

# 保存 (current figure)
pdf.savefig()

# 閉じる
pdf.close()

サンプル1 : 個別に保存

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

x  = np.linspace(0, 2 * np.pi, 100)
y1 = np.sin(x)
y2 = np.cos(x)

pdf = PdfPages('test.pdf')

plt.figure()
plt.plot(x, y1)
pdf.savefig()

plt.figure()
plt.plot(x, y2)
pdf.savefig()

pdf.close()

サンプル2 : 開いているfigureを一括保存

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

x  = np.linspace(0, 2 * np.pi, 100)
y1 = np.sin(x)
y2 = np.cos(x)

plt.figure()
plt.plot(x, y1)

plt.figure()
plt.plot(x, y2)

pdf = PdfPages('test2.pdf')

fignums = plt.get_fignums()
for fignum in fignums:
    plt.figure(fignum)
    pdf.savefig()
    
pdf.close()
21
20
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
21
20

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?