每个文件中的多个图形分别保存为多个文件

我有一个可以读取和运行多个文件并从每个文件生成多个图形的代码。我想分别保存所有数字。但是我只能从每个文件中保存一个数字。例如,我有17个文件,每个文件生成3个数字,所以我总共应该有51个数字。该代码显示所有51个图形(每个文件3个),但每个文件仅保存一个图形,共保存17个图形。如何分别保存所有数字?

    import os
    import numpy as np
    import pandas as pd
    import matplotlib.pyplot as plt

    for file in os.listdir(r'/mydir'):
        if file.endswith(".txt"):
            print(os.path.join("/mydir",file))
            life_time= pd.read_csv(file,sep = "\t")
            life_time.columns = ["Time","Counts"]
            time= life_time.Time[2:599]
            time_1=time-1e-06
            x1=time_1.reset_index(drop=True)
            bin1 = life_time.Counts[2:599]
            bin2 = life_time.Counts[602:1199]
            bin3 = life_time.Counts[1202:1799]
            """Reser the index"""
            r_bin1=bin1.reset_index(drop=True)
            r_bin2=bin2.reset_index(drop=True)
            r_bin3=bin3.reset_index(drop=True)


            x= x1[1:598]
            y1=r_bin1[1:598]
            y2=r_bin2[1:598]
            y3=r_bin3[1:598]
    #From each dataset I have created three y value such as y1,y2,y3 and then created a list
            y = [y1,y3]
            def exponenial_func(x,a,b,c):
                return a*np.exp(-b*x)+c
            for i in y:
                popt,pcov = curve_fit(exponenial_func,x,i)
                a,c = popt
                yy = exponenial_func(x,*popt)
                plt.plot(x,i)
                plt.plot(x,yy,'r--')
                plt.savefig("file{}.jpg".format(file),dpi = 600,bbox_inches = "tight")
                plt.show()

例如,我的文件名为USA_1,USA_2 ......等。我要保存图形名称为USA_1_bin1,USA_1_bin2,USA_1_bin3,USA_2_bin1,USA_2_bin2,USA_2_bin3 ....的图形。...

zhangjuntu 回答:每个文件中的多个图形分别保存为多个文件

我认为您已经省略了执行实际绘图的代码部分。您可以添加它,还是有代表性?没有看到它,我的猜测是您每个循环将生成3个图形,但是通过调用plt.savefig()您仅指的是生成的最后一个图形。例如,如果您这样做:

for file in os.listdir(r'/mydir'):
    data = # something that reads your .txt file into an array or dataframe
    plt.figure()
    plt.plot(data[0],data[1])  # first graph
    plt.figure()
    plt.scatter(data[0],data[2])  # second graph
    plt.figure()
    plt.hist(data[3])  # third graph
    plt.savefig(f"file{file}.jpg")  # f-strings are super cool!

您将生成3个独立的图形,但仅保存最后一个图形,因为您尚未实际指定要保存的图形。解释器仅假设您对最后一个数字感兴趣。解决此问题的一种快速方法是将数字传递给变量,如下所示:

for file in os.listdir(r'/mydir'):
    data = # something that reads your .txt file into an array or dataframe

    fig1 = plt.figure()
    plt.plot(data[0],data[1])  # first graph
    fig2 = plt.figure()
    plt.scatter(data[0],data[2])  # second graph
    fig3 = plt.figure()
    plt.hist(data[3])  # third graph

    # now we can refer to the figures by variable name as save them
    fig1.savefig(f"file{file}_1.jpg")
    fig2.savefig(f"file{file}_2.jpg")
    fig3.savefig(f"file{file}_3.jpg")

现在将创建相同的3个图形,但将分别保存每个图形。但是,我不喜欢这种方法,因为仅调用plt.plot()仍然假定您是最后一个活动图形。更明确的内容将不会有错误的余地,所以我更喜欢这样:

for file in os.listdir(r'/mydir'):
    data = # something that reads your .txt file into an array or dataframe
    # First create your figures and axes
    fig1,ax1 = plt.subplots()
    fig2,ax2 = plt.subplots()
    fig3,ax3 = plt.subplots()

    # Then plot your data on the specific axes
    ax1.plot(data[0],data[1])  # first graph
    ax2.scatter(data[0],data[2])  # second graph
    ax3.hist(data[3])  # third graph

    # now we can refer to the figures by variable name as save them
    fig1.savefig(f"file{file}_1.jpg")
    fig2.savefig(f"file{file}_2.jpg")
    fig3.savefig(f"file{file}_3.jpg")

您还可以引用ax1,ax2,ax3 matplotlib.axes对象来根据需要更改格式,并且不会混淆或依赖于您在代码中编写顺序。

,

好像您要覆盖您的情节三遍。尝试以下方法:

savename = f'{file}'+'_bin'+str(y.index(i)+1)+'.jpg'    
plt.savefig(savename,dpi = 600,bbox_inches = "tight")

就像Kingfischer所建议的那样,我本人也更喜欢它,但是在这种情况下不需要它。

编辑:考虑到y实际上是Series的列表,以下是更合适的解决方案:

for count,i in enumerate(y):
    #other code
    savename = f'{file}'+'_bin'+str(count+1)+'.jpg'    
    plt.savefig(savename,bbox_inches = "tight")
本文链接:https://www.f2er.com/3147478.html

大家都在问