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

alo*_*oha 12 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)
Run Code Online (Sandbox Code Playgroud)

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

alo*_*oha 15

我能够解决它.我的错误是不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()
Run Code Online (Sandbox Code Playgroud)


M4r*_*ini 6

尝试这个。

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)
Run Code Online (Sandbox Code Playgroud)