Hey,
I'm trying to plot a multi-gaussian function to some data, but the code runs a TypeError:
I'm trying to plot a multi-gaussian function to some data, but the code runs a TypeError:
import numpy as np import matplotlib.pyplot as plt import pathlib import os from scipy.optimize import curve_fit #Data data = np.loadtxt('file.hst') x = data[:,0] y1 = data[:,1] # sync1 y2 = data[:,2] # sync2 n_gauss = 2 #Mean & width for y1 & y2 center = sum(x * y1) / sum(y1) #mean = sum(x * y2) / sum(y2) width = np.sqrt(sum(y1 * (x - center)**2) / sum(y1)) #width = np.sqrt(sum(y2 * (x - center)**2) / sum(y2)) #Functions: def multi_gaussian(x, *gaussians): y = gaussians[0] * np.ones_like(x) n_gauss = (len(gaussians)-1) // 3 for gauss in range(n_gauss): y += gaussian(x, gaussians[3*gauss+1], gaussians[3*gauss+2], gaussians[3*gauss+3]) return y def gaussian(x, offset, area, center, width): y = offset + area * np.exp(-(x - center)**2 / (2 * width**2)) return y #Plots: plt.plot(x, y1, label="sync1") plt.plot(x, y2, label="sync2") popt, pcov = curve_fit(gaussian, x, y1, p0=[5000, max(y1), center, width]) #popt, pcov = curve_fit(gaussian, x, y2, p0=[5000, max(y2), center, width]) #plt.plot(x, gaussian(y1, -2100, 3200, center, width), # lw=1, c='m', ls='--', label='Gaussian') plt.plot(x, multi_gaussian(y1, -200, 3200, center, width), lw=1, c='r', ls='--', label='multi-Gaussian') #plt.plot(x, gaussian(y2, 0, 2250, center, width), # lw=1, c='r', ls='--', label='Gaussian') #plt.xlim([850, 980]) #plt.ylim([30, 600]) plt.legend()The error I get is this:
gaussians[3*gauss+3]) TypeError: gaussian() missing 1 required positional argument: 'width'Fitting the single gaussian function works perfectly, but multi_gaussian doesn't work, no matter which n_gauss I use (the same error comes with n_gauss = 1 or 3, f.ex.). Am I not giving the multi_gaussian function enough values, or what could be wrong here? I tried removing offset in case it causes the error, but there is no difference.