Aug-05-2021, 08:09 AM
Hey,
I'm trying to fit a Gaussian function to some data, but I want to return the 'center' and 'width' values and print them. The code returns a ValueError:
I'm trying to fit a Gaussian function to some data, but I want to return the 'center' and 'width' values and print them. The code returns a ValueError:
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] y2 = data[:,2] n_gauss = 1 offset = 0 def gaussian(x, offset, area, center, width): y = area * np.exp(-(x - center)**2 / (2 * width**2)) + offset return y, center, width 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, offset, gaussians[3*gauss+1], gaussians[3*gauss+2], gaussians[3*gauss+3]) return y #Plots: plt.plot(x, y1, label="sync1") plt.plot(x, y2, label="sync2") popt, pcov = curve_fit(gaussian, x, y1, p0=[0, max(y1), 900, 120]) #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, -210, 270, 900, 120), lw=1, c='r', ls='--', label='multi-Gaussian') #plt.plot(x, gaussian(y2, 0, 2250, 900, 120), # lw=1, c='r', ls='--', label='Gaussian') #plt.xlim([850, 980]) #plt.ylim([30, 600]) plt.legend() #Outputs #print("Center: ", center) #print("Width: ", width)The error is this:
return func(xdata, *params) - ydata ValueError: operands could not be broadcast together with shapes (3,) (1201,)and there is thus no plot. Removing 'center' and 'width' from the return line in the Gaussian function solves the problem, but I don't know how to get those values out from the fitting otherwise. Any advice?