Python Matplotlib绘图迭代绘图要素
我正在编写一个Python脚本,它将循环遍历目录中的每个ASCII文件,并输出包含在该文件中的数据的单独绘图。此外,它还可以找到最佳曲线拟合参数并将其输出到一个组合文本文件中 文本输出工作正常,但打印输出不正常。在第一次迭代中,它可以正常工作,但在那之后,它会迭代绘图功能。例如,在os.listdir(目录)中文件名的第三次迭代中,将绘制三个图例标签、三条拟合曲线和每个数据点三次。以下是一个屏幕截图: 以下是我正在使用的代码:Python Matplotlib绘图迭代绘图要素,python,matplotlib,plot,Python,Matplotlib,Plot,我正在编写一个Python脚本,它将循环遍历目录中的每个ASCII文件,并输出包含在该文件中的数据的单独绘图。此外,它还可以找到最佳曲线拟合参数并将其输出到一个组合文本文件中 文本输出工作正常,但打印输出不正常。在第一次迭代中,它可以正常工作,但在那之后,它会迭代绘图功能。例如,在os.listdir(目录)中文件名的第三次迭代中,将绘制三个图例标签、三条拟合曲线和每个数据点三次。以下是一个屏幕截图: 以下是我正在使用的代码: for filename in os.listdir(direct
for filename in os.listdir(directory):
if filename.endswith((".lc", ".lc1")):
wf = directory + "/" + filename
try:
# get the data
time, flux = getData(wf, nheader)
# fit the data
popt_sine, err_sine = sineFit(time, flux)
popt_exp, err_exp = expFit(time, flux)
# plot/save the data
plotData(filename, time, flux, popt_sine, popt_exp)
# output the data
output = outputData(popt_sine, err_sine, popt_exp, err_exp)
print(output)
except StopIteration:
raise IOError("End of File Error")
其中,我将函数plotData定义为:
def plotData(filename, time, flux, popt_sine, popt_exp):
t = np.linspace(time[0], time[len(time)-1], 10000)
# Sine plot
A = popt_sine[0]
B = popt_sine[1]
C = popt_sine[2]
D = popt_sine[3]
plt.plot(t, sine(t, A, B, C, D), "r", label="Sine Fit")
# Exponential plot
E = popt_exp[0]
F = popt_exp[1]
G = popt_exp[2]
H = popt_exp[3]
#plt.plot(t, exponential(t, E, F, G, H), label='Exponential Fit')
# Raw plot
plt.plot(time, flux, "ko", label = "Data")
# Plot config.
plt.xlabel("Time (sec)")
plt.ylabel("Flux")
plt.title("Mean Normalized Flux vs. Time (" + filename + ")")
plt.legend(loc='best')
# save plot
if filename.endswith(".lc"):
plt.savefig(filename[:-3] + ".jpg")
elif filename.endswith(".lc1"):
plt.savefig(filename[:-4] + ".jpg")
else:
raise ValueError("Incorrect input file type")
#plt.show()
我注意到一件有趣的事情:如果我不保存绘图,而是分别查看和退出每个绘图,那么每个绘图都是正确的。我认为您只需要在循环的每次迭代中(或在“plotData”函数中)使用
plt.figure()
创建一个新图形即可。谢谢你的帮助。