将绘图保存为PDF格式

2024-04-19 06:22:56 发布

您现在位置:Python中文网/ 问答频道 /正文

绘图模块

def plotGraph(X,Y):
    fignum = random.randint(0,sys.maxint)
    plt.figure(fignum)
    ### Plotting arrangements ###
    return fignum

主模块

import matplotlib.pyplot as plt
### tempDLStats, tempDLlabels are the argument
plot1 = plotGraph(tempDLstats, tempDLlabels)
plot2 = plotGraph(tempDLstats_1, tempDLlabels_1)
plot3 = plotGraph(tempDLstats_2, tempDLlabels_2)
plt.show()

我想把所有的图形plot1,plot2,plot3保存到一个PDF文件中。有什么办法可以实现吗?我不能在主模块中包含plotGraph函数。

有一个名为pylab.savefig的函数,但它似乎只在与绘图模块一起放置时才起作用。有没有别的方法来完成它?


Tags: 模块函数绘图defsyspltrandomrandint
3条回答

如果有人从谷歌来到这里,想把一个数字转换成一个.pdf文件(这就是我要找的):

import matplotlib.pyplot as plt

f = plt.figure()
plt.plot(range(10), range(10), "o")
plt.show()

f.savefig("foo.pdf", bbox_inches='tight')
import datetime
import numpy as np
from matplotlib.backends.backend_pdf import PdfPages
import matplotlib.pyplot as plt

# Create the PdfPages object to which we will save the pages:
# The with statement makes sure that the PdfPages object is closed properly at
# the end of the block, even if an Exception occurs.
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=True)
    plt.figure(figsize=(8, 6))
    x = np.arange(0, 5, 0.1)
    plt.plot(x, np.sin(x), 'b-')
    plt.title('Page Two')
    pdf.savefig()
    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()

对于单个pdf文件中的多个绘图,可以使用PdfPages

plotGraph函数中,您应该返回图形,而不是调用图形对象的savefig

----绘图模块---

def plotGraph(X,Y):
      fig = plt.figure()
      ### Plotting arrangements ###
      return fig

----绘图模块---

----主模块----

from matplotlib.backends.backend_pdf import PdfPages

plot1 = plotGraph(tempDLstats, tempDLlabels)
plot2 = plotGraph(tempDLstats_1, tempDLlabels_1)
plot3 = plotGraph(tempDLstats_2, tempDLlabels_2)

pp = PdfPages('foo.pdf')
pp.savefig(plot1)
pp.savefig(plot2)
pp.savefig(plot3)
pp.close()

相关问题 更多 >