import datetime import numpy as np from matplotlib.backends.backend_pdf import PdfPages import matplotlib.pyplot as plt
with PdfPages('multipage_pdf.pdf') as pdf: plt.figure(figsize=(3, 3)) plt.plot(range(7), [3, 1, 4, 1, 5, 9, 2], 'r-o') plt.title('Page One') pdf.savefig() # saves the current figure into a pdf page plt.close()
plt.rc('text', usetex=False) fig = plt.figure(figsize=(4, 5)) plt.plot(x, x*x, 'ko') plt.title('Page Three') pdf.savefig(fig) # or you can pass a Figure object to pdf.savefig plt.close()
# We can also set the file's metadata via the PdfPages object: d = pdf.infodict() d['Title'] = 'Multipage PDF Example' d['Author'] = u'Jouni K. Sepp\xe4nen' d['Subject'] = 'How to create a multipage pdf file and set its metadata' d['Keywords'] = 'PdfPages multipage keywords author title subject' d['CreationDate'] = datetime.datetime(2009, 11, 13) d['ModDate'] = datetime.datetime.today()
4. 避免图形显示
如果不想显示图形,只想保存,可以使用非交互后端(如Agg):
1 2 3 4 5
import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt plt.plot([1,2,3]) plt.savefig('myfig')
核心代码
以下是一个完整的示例代码,展示了如何保存图形并避免显示:
1 2 3 4 5 6
import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt