Reputation: 189
I have data and I am fitting the data with a gaussian curve fitting. The blue bullets are my data. The gaussian starts at zero and look like the red curve. But I want something, that looks more like the green curve. All gaussian curve fitting examples I found at the internet starts at zero. Maybe there is another function that can change the starting y value or something like that?
Here's my code so far:
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
import numpy as np
import os
import csv
path = 'Proben Bilder v06 results'
filename = '00_sumListe.csv'
# read csv file with scale data
x = []
y = []
with open(os.path.join(path, filename), 'r') as csvfile:
sumFile = csv.reader(csvfile, delimiter=',')
for row in sumFile:
id = float(row[0])
sumListe = -float(row[1])
x = np.append(x, id)
y = np.append(y, sumListe)
y = y-min(y)
# x = np.arange(10)
# y = np.array([0, 1, 2, 3, 4, 5, 4, 3, 2, 1])
# weighted arithmetic mean (corrected - check the section below)
mean = sum(x * y) / sum(y)
sigma = np.sqrt(sum(y * (x - mean)**2) / sum(y))
def gauss(x, a, x0, sigma): # x0 = mü
return a * np.exp(-(x - x0)**2 / (2 * sigma**2))
popt, pcov = curve_fit(gauss, x, y, p0=[max(y), mean, sigma])
# plt.gca().invert_yaxis()
plt.plot(x, y, 'b+:', label='data')
plt.plot(x, gauss(x, *popt), 'r-', label='fit')
plt.legend()
plt.title('Fig. 3 - Fit for Time Constant')
plt.xlabel('steps')
plt.ylabel('mean value')
plt.show()
My data is a bit to big to write it here... I can't load it up or can I?
Does anyone have a better idea?
Upvotes: 4
Views: 1171
Reputation: 25363
You could modify your gauss function so that there is an offset in the y axis to potentially give you a better fit. This requires you to add an extra initial guess in p0
# your code here
def gauss2(x, b, a, x0, sigma):
return b + (a * np.exp(-(x - x0) ** 2 / (2 * sigma ** 2)))
popt, pcov = curve_fit(gauss2, x, y, p0=[10, max(y), mean, sigma])
Upvotes: 4