将循环中生成的轮廓图像保存为单个pdf文件(最好每页2张图像)

2024-05-01 21:58:31 发布

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

我写了这段代码,它将生成许多等高线图,每个等高线图对应于一个单独的文本文件。我有多个文本文件。目前,我能够生成所有的图像单独在png格式没有任何问题。 当我尝试将图像保存为pdf文件时,它只保存循环中生成的最后一个图像。这个问题与我之前发布的问题类似,但有一个不同的问题。Similar

问题:我希望能够从python自动将所有图像生成到单个pdf文件中。例如,如果我有100个文本文件,那么我想把这100个图像全部保存到一个pdf文件中文件。还有理想情况下,我想保存2个图像在一个单独的页面在pdf文件。这里面有一些问题,但我找不到合适的解决办法。因为我有很多案例需要生成图像,所以我想将它们保存为单个pdf文件,因为这样更容易分析它们。如果您能给我一些建议/建议,我将不胜感激。在

这是示例文本文件Sample Text的链接 通用电气公司

from __future__ import print_function
import numpy as np
from matplotlib import pyplot as plt
from scipy.interpolate  import griddata
from matplotlib.backends.backend_pdf import PdfPages
path = 'location of the text files'
FT_init = 5.4311
delt = 0.15
TS_init = 140
dj_length = 2.4384

def streamfunction2d(y,x,Si_f,q):       
  with PdfPages('location of the generated pdf') as pdf:  
        Stf= plt.contour(x,y,Si_f,20)
        Stf1 = plt.colorbar(Stf)
        plt.clabel(Stf,fmt='%.0f',inline=True)
        plt.figtext(0.37,0.02,'Flowtime(s)',style= 'normal',alpha=1.0)
        plt.figtext(0.5,0.02,str(q[p]),style= 'normal',alpha=1.0)
        plt.title('Streamfunction_test1')
        plt.hold(True)       
        plt.tight_layout()
        pdf.savefig()

        path1 = 'location where the image is saved'
        image = path1+'test_'+'Stream1_'+str((timestep[p]))+'.png'
        plt.savefig(image)    
        plt.close() 

timestep = np.linspace(500,600,2)
flowtime = np.zeros(len(timestep))
timestep = np.array(np.round(timestep),dtype = 'int')
###############################################################################
for p in range(len(timestep)):   
        if timestep[p]<TS_init:
            flowtime[p] = 1.1111e-01
        else:
            flowtime[p] = (timestep[p]-TS_init)*delt+FT_init 
        q = np.array(flowtime)

        timestepstring=str(timestep[p]).zfill(4)
        fname = path+"ddn150AE-"+timestepstring+".txt"
        f = open(fname,'r')
        data = np.loadtxt(f,skiprows=1)
        data = data[data[:, 1].argsort()]
        data = data[np.logical_not(data[:,11]== 0)]                                                                
        Y  = data[:,2]  # Assigning Y to column 2 from the text file
        limit = np.nonzero(Y==dj_length)[0][0]
        Y  = Y[limit:]

        Vf  = data[:,11] 
        Vf  = Vf[limit:]
        Tr  = data[:,9]  
        Tr  = Tr[limit:]

        X  = data[:,1]  
        X  = X[limit:]
        Y  = data[:,2]  
        Y  = Y[limit:]
        U  = data[:,3]  
        U  = U[limit:]
        V  = data[:,4]  
        V  = V[limit:]
        St = data[:,5]  
        St  = St[limit:]
        ###########################################################################     

        ## Using griddata for interpolation from Unstructured to Structured data
        # resample onto a 300x300 grid        
        nx, ny = 300,300

        # (N, 2) arrays of input x,y coords and dependent values
        pts = np.vstack((X,Y )).T
        vals = np.vstack((Tr))
        vals1 = np.vstack((St))

        # The new x and y coordinates for the grid
        x = np.linspace(X.min(), X.max(), nx)
        y = np.linspace(Y.min(), Y.max(), ny)
        r = np.meshgrid(y,x)[::-1]

        # An (nx * ny, 2) array of x,y coordinates to interpolate at
        ipts = np.vstack(a.ravel() for a in r).T 

        Si = griddata(pts, vals1, ipts, method='linear')
        print(Ti.shape,"Ti_Shape")
        Si_f = np.reshape(Si,(len(y),len(x)))
        print(Si_f.shape,"Streamfunction Shape")        
        Si_f = np.transpose(Si_f)        
        streamfunction2d(y,x,Si_f,q) 

Tags: 文件ofthefrom图像importdatapdf
1条回答
网友
1楼 · 发布于 2024-05-01 21:58:31

编辑:正如您所提到的,matplotlib可能能够使用^{}函数自己处理所有事情。见this related answer。我最初的回答是黑客攻击。在

我认为代码中的错误是每次遍历循环时都会创建另一个PdfPage对象。我的建议是将PdfPage对象作为参数添加到streamfunction2d函数中,并在循环之前一次性地创建PdfPage对象(使用with语句,如documentation似乎是个好主意)。在

示例:

def streamfunction2d(y,x,Si_f,q,pdf):       
    # (...)
    pdf.savefig(plt.gcf()) 

with PdfPages('output.pdf') as pdf:
   for p in range(len(timestep)): 
      # (...)  
      streamfunction2d(y,x,Si_f,q,pdf)

原始答案: 这是一个使用^{}软件的快速而肮脏的解决方案。在

^{pr2}$

它使用两个东西:

  • 可以使用matplotlib的savefig命令将图形保存为pdf。在
  • 您可以使用subprocess库调用其他程序。我使用pdfunite合并所有页面。确保您的机器上有它!在

如果你想一页一页地有几个图,你可以使用子图。在

或者,您可以使用另一个python库(比如pyPDF)来合并页面,但是它需要稍微多一些代码。以下是一个(未经测试的)示例:

from matplotlib import pyplot as plt
import numpy as np
from pyPdf import PdfFileWriter, PdfFileReader

# create an empty pdf file
output = PdfFileWriter()

X = np.linspace(0,1,100)
for i in range(10):
    # random plot
    plt.plot(X,np.cos(i*X))

    # Save each figure as a pdf file.
    fi = "page_{:0}.pdf".format(i)
    plt.savefig(fi)
    plt.clf()

    # add it to the end of the output
    input = PdfFileReader(file(fi, "rb"))
    output.addPage(input.getPage(0))

# Save the resulting pdf file. 
outputStream = file("document-output.pdf", "wb")
output.write(outputStream)

相关问题 更多 >