Skip to main content
 首页 » 编程设计

python之matplotlib PdfPages 复合图像

2024年11月01日10itcoder

我正在遍历大量字符串,并使用 matplotlib 的 PdfPages 后端为每个字符串制作一个 PDF 文件。当我一次只做一个(而不是遍历所有字符串)时,效果很好。然而,当我迭代时,我得到大量额外的行,这些行与我的图例中的任何内容都不对应,这让我很困惑。我怀疑这是在我需要它之后卡在周围的物体的一些问题。这是我正在编写的伪代码:

import matplotlib 
matplotlib.use('Agg') 
import matplotlib.pyplot as plt 
from matplotlib.backends.backend_pdf import PdfPages 
 
def main(): 
    stringList = import(stringList) #Not an actual function, this is just where I get my list 
    for s in stringList: 
        pp = PdfPages(s+'.pdf') 
        plotData(s, pp) 
        pp.close() 
 
def plotData(s, pp): 
    dataList1, dataList2 = importData(s) #Again, not an actual function, just getting my data 
 
    #Make first figure 
    firstFig = plt.figure("first") 
    firstax = firstFig.add_subplot(111) 
    firstFig.suptitle("First") 
    xaxis = [x for x in range(len(dataList1))] 
    firstax.plot(xaxis, dataList2, label='local max') 
    tempax.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3, 
       ncol=2, mode="expand", borderaxespad=0.) 
    pp.savefig() 
 
    #Make second figure 
    #Exactly the same thing.... 
 
    #Make third figure 
    #Exactly the same thing... 

同样,我认为这与我如何使用这些对象有关,并且文档非常枯燥(我保证我已经研究了一整天),但如果有人知道这里发生了什么,我不胜感激!

请您参考如下方法:

通过将字符串指定为 plt.figure() 的参数,您可以重复使用相同的数字 每次通过循环。处理这个问题的最简单方法就是不指定字符串并使用

fig = plt.figure() 

放个

也不错
plt.close('all') 

在每个循环的底部释放 pyplot 对图形对象的所有引用。