Python 将多个图形保存到一个 PDF 文件中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17788685/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python saving multiple figures into one PDF file
提问by Ahmed Niri
In python (for one figure created in a GUI) I was able to save the figure under .jpg and also .pdf by either using:
在 python 中(对于在 GUI 中创建的图形),我可以使用以下任一方法将图形保存在 .jpg 和 .pdf 下:
plt.savefig(filename1 + '.pdf')
or
或者
plt.savefig(filename1 + '.jpg')
Using one file I would like to save multiple figures in either .pdf or .jpg (just like its done in math lab). Can anybody please help with this?
使用一个文件,我想以 .pdf 或 .jpg 格式保存多个数字(就像在数学实验室中所做的那样)。有人可以帮忙吗?
采纳答案by Mind Mixer
Use PdfPages
to solve your problem. Pass your figure
object to the savefig
method.
使用PdfPages
为您解决问题。将您的figure
对象传递给savefig
方法。
For example, if you have a whole pile of figure
objects open and you want to save them into a multi-page PDF, you might do:
例如,如果您figure
打开了一大堆对象,并且想要将它们保存到多页 PDF 中,您可以这样做:
import matplotlib.backends.backend_pdf
pdf = matplotlib.backends.backend_pdf.PdfPages("output.pdf")
for fig in xrange(1, figure().number): ## will open an empty extra figure :(
pdf.savefig( fig )
pdf.close()
回答by Brett Morris
Do you mean save multiple figures intoone file, or save multiple figures using one script?
您的意思是将多个图形保存到一个文件中,还是使用一个脚本保存多个图形?
Here's how you can save two different figures using one script.
以下是使用一个脚本保存两个不同图形的方法。
>>> from matplotlib import pyplot as plt
>>> fig1 = plt.figure()
>>> plt.plot(range(10))
[<matplotlib.lines.Line2D object at 0x10261bd90>]
>>> fig2 = plt.figure()
>>> plt.plot(range(10,20))
[<matplotlib.lines.Line2D object at 0x10263b890>]
>>> fig1.savefig('fig1.png')
>>> fig2.savefig('fig2.png')
...which produces these two plots into their own ".png" files:
...将这两个图生成到它们自己的“.png”文件中:
To save them to the same file, use subplots:
要将它们保存到同一个文件中,请使用子图:
>>> from matplotlib import pyplot as plt
>>> fig = plt.figure()
>>> axis1 = fig.add_subplot(211)
>>> axis1.plot(range(10))
>>> axis2 = fig.add_subplot(212)
>>> axis2.plot(range(10,20))
>>> fig.savefig('multipleplots.png')
The above script produces this single ".png" file:
上面的脚本生成这个单一的“.png”文件: