Saving plots to pdf files using matplotlib

匿名 (未验证) 提交于 2019-12-03 01:48:02

问题:

I want to save more than 1 plot to a pdf file. Here is my code:

import matplotlib.pyplot as plt from matplotlib.backends.backend_pdf import PdfPages  def function_plot(X,Y):     plt.figure()     plt.clf()      pp = PdfPages('test.pdf')      graph = plt.title('y vs x')     plt.xlabel('x axis', fontsize = 13)     plt.ylabel('y axis', fontsize = 13)     pp.savefig(graph)   function_plot(x1,y1) function_plot(x2,y2) 

I know that my ideas are scrambled but I can't find the way to write my code. The thing is that I need my graphs to have labeled x and y axis.

回答1:

I was able to solve it. My mistake was that pp.savefig() should not take arguments.

Here is my final code:

from matplotlib.backends.backend_pdf import PdfPages import numpy as np import matplotlib.pyplot as plt  x1 = np.arange(10) y1 = x1**2  x2 = np.arange(20) y2 = x2**2  pp = PdfPages('test.pdf')   def function_plot(X,Y):     plt.figure()     plt.clf()      plt.plot(X,Y)     plt.title('y vs x')     plt.xlabel('x axis', fontsize = 13)     plt.ylabel('y axis', fontsize = 13)     pp.savefig()  function_plot(x1,y1) function_plot(x2,y2)  pp.close() 


回答2:

Try this.

from matplotlib.backends.backend_pdf import PdfPages import numpy as np import matplotlib.pyplot as plt  x1 = np.arange(10) y1 = x1**2  x2 = np.arange(20) y2 = x2**2  def function_plot(X,Y, pp):     plt.figure()     plt.clf()      plt.plot(X,Y)     graph = plt.title('y vs x')     plt.xlabel('x axis', fontsize = 13)     plt.ylabel('y axis', fontsize = 13)     pp.savefig(plt.gcf())   with PdfPages('test.pdf') as pp:     function_plot(x1,y1, pp)     function_plot(x2,y2, pp) 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!