使用matplotlib将图表保存为pdf文件

时间:2014-01-26 14:12:37

标签: python matplotlib pdfpages

我想将超过1个绘图保存到pdf文件中。这是我的代码:

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)

我知道我的想法很乱,但我找不到编写代码的方法。问题是我需要我的图形标记x和y轴。

2 个答案:

答案 0 :(得分:14)

我能够解决它。我的错误是pp.savefig()不应该接受争论。

这是我的最终代码:

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()

答案 1 :(得分:3)

试试这个。

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)