【问题标题】:Have a problem with saving figures in matplotlib在 matplotlib 中保存数字时遇到问题
【发布时间】:2021-10-27 18:26:19
【问题描述】:

我在保存数字时遇到了问题。此代码对信号进行 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.clf() 放在plt.savefig 之后。如果这有帮助,请告诉我。

标签: python python-3.x matplotlib fft


【解决方案1】:

我认为问题在于您继续在同一个图中工作。尝试执行以下操作之一:

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

plt.figure()

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

plt.close('all')

【讨论】:

  • 是的,你是对的,谢谢
  • @VasylSokolenko 如果此答案解决了您的问题,您应该考虑有机会批准它,单击答案左侧的复选标记。
猜你喜欢
  • 1970-01-01
  • 2017-09-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-29
  • 1970-01-01
相关资源
最近更新 更多