How can I fit my plots from measured data?

2020-07-27 02:40发布

问题:

How can I fit my plots?

Up to now, I've got the following code, which plots a variety of graphs from an array (data from an experiment) as it is placed in a loop:

import matplotlib as plt
plt.figure(6)
plt.semilogx(Tau_Array, Correlation_Array, '+-')
plt.ylabel('Correlation')
plt.xlabel('Tau')
plt.title("APD" + str(detector) + "_Correlations_log_graph")
plt.savefig(DataFolder + "/APD" + str(detector) + "_Correlations_log_graph.png")

This works so far with a logarithmic plot, but I am wondering how the fitting process could work right here. In the end I would like to have some kind of a formula or/and a graph which best describes the data I measured.

I would be pleased if someone could help me!

回答1:

You can use curve_fit from scipy.optimize for this. Here is an example

# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit

def func(x,a):
   return np.exp(a*x)

x,y,z = np.loadtxt("fit3.dat",unpack=True)

popt,pcov = curve_fit(func,x,y)
y_fit = np.exp(popt[0]*x)


plt.plot(x,y,'o')
plt.errorbar(x,y,yerr=z)
plt.plot(x,y_fit)
plt.savefig("fit3_plot.png")
plt.show()

In yourcase, you can define the func accordingly. popt is an array containing the value of your fitting parameters.