简体   繁体   English

在一个PDF页面Matplotlib中保存多个图形

[英]Save multiple figures in one pdf page, matplotlib

I'm trying to get my figures in just one pdf page, but I don't know how to do this. 我正在尝试仅在一个pdf页面中获取数据,但是我不知道该怎么做。 I found out that it's possible to save multiple figures in a pdf file with 'matplotlib.backends.backend_pdf', but it doesn't work for just one page. 我发现可以使用“ matplotlib.backends.backend_pdf”将多个图形保存在pdf文件中,但是它仅对一页无效。 Has anyone any ideas ? 有任何想法吗? Convert the figures to just one figure ? 将数字转换成一个数字?

You can use matplotlib gridspec to have multiple plots in 1 window 您可以使用matplotlib gridspec在1个窗口中包含多个图

http://matplotlib.org/users/gridspec.html http://matplotlib.org/users/gridspec.html

from matplotlib.gridspec import GridSpec
import random
import numpy
from matplotlib import pyplot as pl

fig = pl.figure(figsize=(12, 16))
G = GridSpec(2,2)   
axes_1 = pl.subplot(G[0, :])

x = [random.gauss(3,1) for _ in range(400)]
bins = numpy.linspace(-10, 10, 100)
axes_1.hist(x, bins, alpha=0.5, label='x')

axes_2 = pl.subplot(G[1, :])
axes_2.plot(x)

pl.tight_layout()
pl.show()

You can change the rows and column values and can subdivide the sections. 您可以更改行和列的值,并可以细分各个部分。

Here is a solution provided by matplotlib: 这是matplotlib提供的解决方案:

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

with PdfPages('foo.pdf') as pdf:
    #As many times as you like, create a figure fig and save it:
    fig = plt.figure()
    pdf.savefig(fig)

    ....
    fig = plt.figure()
    pdf.savefig(fig) 

Voilà

Find a full example here: multipage pdf matplotlib 在此处找到完整的示例: 多页pdf matplotlib

And by the way, for one figure, you don't need matplotlib.backends.backend_pdf just add pdf extension like so: 顺便说一句,对于一个数字,您不需要matplotlib.backends.backend_pdf只需添加pdf扩展名,如下所示:

plt.savefig("foo.pdf")

The PDF backend makes one page per figure. PDF后端每个图一页。 Use subplots to get multiple plots into one figure and they'll all show up together on one page of the PDF. 使用子图将多个图绘制成一个图形,它们都将一起显示在PDF的一页上。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM