繁体   English   中英

在 matplotlib 中保存数字时出现问题

[英]Have a problem with saving figures in matplotlib

我在保存数字时遇到问题。 此代码对信号进行 FFT,然后应将 FFT 保存在 .png 中的单独文件中。 第一张图没问题,但下一张图上有所有以前的FFT,也许这是一个典型的问题,你知道如何解决吗?

import numpy as np
import matplotlib.pyplot as plt
import glob

txt_files = glob.glob("*.pom") #format of files
print(txt_files)


for i in range(len(txt_files)):

    
    mat = np.genfromtxt(txt_files[i])
    #x = np.delete(mat, [0, 6] , axis=0)
    a = np.delete(mat, 0, axis=1)
    b = mat[1, 0] - mat[0, 0]

    std = a.std()
    mean = a.mean()

    print(std, mean)

    Fs = 5000  # sumpling freq IF TIME IN FIRST COLUMN
    tstep = 1 / Fs  # sumple time interval

    N = np.size(a)  # number of samples

    t = np.linspace(0, (N - 1) * tstep, N)  # time step
    fstep = Fs / N
    f = np.linspace(0, (N - 1) * fstep, N)  # freq step

    X = np.fft.fft2(a)
    X_mag = np.abs(X) / N

    f_plot = f[0:int(N / 2 + 1)]

    X_mag_plot = 2 * X_mag[0:int(N / 2 + 1)]
    X_mag_plot[0] = X_mag_plot[0] / 2

    plt.plot(f_plot, X_mag_plot, "-k", linewidth=0.5)
    plt.xlabel('Frequency [Hz]')
    plt.ylabel('Amplitude')
    plt.xscale("log")
    plt.axis([1, 1000, 0, 0.01])
    plt.grid(True)
    #plt.text(45, .025, r'$\mu=100,\ \sigma=15$', backgroundcolor="w")
    plt.text(300, 0.01, f'std={std:.3f} \nmean={mean:.3f}', backgroundcolor="w")

    #plt.show()

    np.savetxt(txt_files[i] + "_Widmo.txt", X_mag_plot, delimiter="\t")
    plt.savefig(txt_files[i] + ".png", dpi=250)
    if i == 1:
        np.savetxt(txt_files[0] + "_Fs.txt", f_plot, delimiter="\t")
    del f_plot
    del X_mag_plot
    del txt_files[i]

我认为问题在于您继续以相同的数字工作。 尝试执行以下操作之一:

在循环的每次迭代中打开一个新图窗。 这不是最佳选择,因为您可能会打开很多数字:

plt.figure()

另一个更优化的选项是在保存图形后在每次迭代中关闭图形:

plt.close('all')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM