Arbeiten mit scipy
Ein Versuch Kurvenfitting zu verstehen.
Anpassen einer Funktion an Daten aus einem Histogramm.
Ein Peak von normal (Gauß'schen) verteilten Daten Zeile 21
Exponentiell abklingender Hintergrund. Zeile 11
Durch gegenseitige Veränderung kann (optimal zunächst )
dann auch durch Verlauf der Exponentialfunktion
der Peak bei x = und umgekhrt der Peak (Normalverteilung)
verschoben werden. Art und Menge ()
So erklärt sich der Zusanmmenhang zwischen Datenmenge(size),
Art der Daten(angewandte Verteilung)
Neben dem Plot werden auh die Koordinaten angezeigt.
G ute Zeit OSWALD
Code: Alles auswählen
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
# 2.) Define fit function.
def fit_function(x, A, beta, B, mu, sigma):
return (A * np.exp(-x/beta) + B * np.exp(-1.0 * (x - mu)**2 / (2 * sigma**2)))
# 3.) Eexponential-Funktion und gauss-Daten sowie Histogramm erzeugen
data = np.random.exponential(scale=2.0, size=100000)
data2 = np.random.normal(loc=3.0, scale=0.3, size=150000)
bins = np.linspace(0, 6, 61)
data_entries_1, bins_1 = np.histogram(data, bins=bins)
data_entries_2, bins_2 = np.histogram(data2, bins=bins)
# 4.) Add histograms of exponential and gaussian data.
data_entries = data_entries_1 + data_entries_2
binscenters = np.array([0.5 * (bins[i] + bins[i+1]) for i in range(len(bins)-1)])
# 5.) Fit the function to the histogram data.
popt, pcov = curve_fit(fit_function, xdata=binscenters, ydata=data_entries, p0=[20000, 2.0, 2000, 3.0, 0.3])
print(popt)
# 6.)
# Generate enough x values to make the curves look smooth.
xspace = np.linspace(0, 6, 100000)
# Plot the histogram and the fitted function.
plt.bar(binscenters, data_entries, width=bins[1] - bins[0], color='navy', label=r'Histogram Einträge')
plt.plot(xspace, fit_function(xspace, *popt), color='red', linewidth=2.5, label=r'Angepasster Funktionsverlauf ')
# Make the plot nicer.
plt.xlim(0,10)
plt.xlabel(r'x - Achse')
plt.ylabel('Anzahl der Eintragungen')
plt.title('Exponentiell abfallend mit ''Gauss peak')
plt.legend(loc='best')
plt.show()