Skip to content

Instantly share code, notes, and snippets.

@JasonGoemaat
Created September 29, 2025 00:04
Show Gist options
  • Select an option

  • Save JasonGoemaat/d2f258431e394e2cab39858efd9fca66 to your computer and use it in GitHub Desktop.

Select an option

Save JasonGoemaat/d2f258431e394e2cab39858efd9fca66 to your computer and use it in GitHub Desktop.
Python matplotlib polyfill
# fit.py
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import mean_squared_error
# Your data
ms = np.array([1, 100, 200, 300, 400, 500, 600, 650, 700, 750, 800, 900])
adjusted = np.array([1, 7, 25, 46, 92, 168, 242, 299, 366, 410, 511, 641])
# Try polynomial fits of degrees 2 to 4
fits = {}
errors = {}
for deg in range(2, 5):
coeffs = np.polyfit(ms, adjusted, deg)
print(deg, 'coeffs', coeffs)
poly = np.poly1d(coeffs)
prediction = poly(ms)
mse = mean_squared_error(adjusted, prediction)
fits[deg] = poly
errors[deg] = mse
# Find best fit (lowest mean squared error)
best_deg = min(errors, key=errors.get)
best_fit = fits[best_deg]
# Show best polynomial formula
print(f"Best degree: {best_deg}")
print("Best fit polynomial:")
print(best_fit)
# Plot data and best-fit curve
ms_fit = np.linspace(min(ms), max(ms), 500)
adjusted_fit = best_fit(ms_fit)
plt.figure(figsize=(10, 6))
plt.scatter(ms, adjusted, color='red', label='Actual Data')
plt.plot(ms_fit, adjusted_fit, label=f'Best Fit (Degree {best_deg})', color='blue')
plt.xlabel('ms')
plt.ylabel('Adjusted')
plt.title('Best Polynomial Fit to Data')
plt.legend()
plt.grid(True)
plt.tight_layout()
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment