Skip to content

Instantly share code, notes, and snippets.

@mikemhenry
Created April 23, 2018 03:31
Show Gist options
  • Save mikemhenry/80be168021a85f762ac28436dbbb4836 to your computer and use it in GitHub Desktop.
Save mikemhenry/80be168021a85f762ac28436dbbb4836 to your computer and use it in GitHub Desktop.
Curve fitting with python
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import curve_fit
x = np.linspace(0,100)
noise = np.random.normal(0, 2, len(x))
simulated_data = x*3 + 5 + noise
def func(x, m, b):
return m*x + b
params = curve_fit(func, x, simulated_data)
m, b = params[0]
print("m=", m, " b=", b)
plt.plot(x, m*x + b, label="fit")
plt.plot(x, simulated_data, label="sim data", alpha=0.5)
plt.legend()
plt.savefig("test.png")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment