2012-07-04 3 views
35

------ черчения модуль ------Matplotlib.pyplot: Сохранение графики в PDF

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

------ черчения модуль ------

----- mainModule ----

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 в mainModule.

Существует функция под названием «pylab.savefig», но это работает, только если она размещена вместе с модулем построения. Есть ли другой способ сделать это? Предложите мне какие-либо изменения в моих функциональных кодах, чтобы я мог сохранять графики в один файл PDF.

ответ

-9

Не берите в голову, как это сделать.

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

------ черчения модуль ------

----- mainModule ----

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.savefig('plot1.png') 
plot2.savefig('plot2.png') 
plot3.savefig('plot3.png') 

----- mainModule - ---

+13

Подождите, я думал, что вы хотите сохранить графики в одном файле PDF. Ваше решение сохраняет изображения в трех отдельных файлах PNG, что похоже на ответ на другой вопрос. – DSM

+0

Чрезвычайно извините. Я как-то больше конкретизировал сохранение файла. Я знал о бэкэнде pdf, но получил свою работу и пренебрег ее добавлением. В любом случае, спасибо, что указали это. – VoodooChild92

+1

Увидев количество downvotes, вы можете подумать об удалении этого ответа, чтобы оставить «комнату» для других ответов. – PatrickT

77

Для нескольких участков в один файл в формате PDF вы можете использовать PdfPages

В plotGraph весело вы должны вернуть фигуру и позвонить по номеру savefig объекта фигуры.

------ черчения модуль ------

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

------ черчения модуль ------

----- mainModule - ---

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

Если кто-то заканчивает здесь от Google, глядя преобразовать один рисунок в формате .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') 
+0

Это было легко ... – Tunn

+1

Как установить размер страницы в формате pdf? – wherestheforce

+0

@wherestheforce Я не уверен, что вы можете напрямую установить формат PDF, но вы можете изменить размер фигуры: f = plt.figure (figsize = (5, 10)), например, чтобы изменить коэффициент pdf. –

Смежные вопросы