Created
May 13, 2025 18:11
-
-
Save todbot/e2e192f228c67ccb4b05c2a02e761eb8 to your computer and use it in GitHub Desktop.
reminder to me about how to use pyplot and np.polyfit
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
import matplotlib.pyplot as plt | |
# Original data points | |
x_vals = np.array([-0.5, -23.6, -58.3]) | |
y_vals = np.array([1, 47, 110]) | |
# Linear regression (best-fit line) | |
coeffs = np.polyfit(x_vals, y_vals, 1) | |
linear_fit = coeffs[0] * x_vals + coeffs[1] | |
# f(x) = -2x | |
fx_test = -2 * x_vals | |
# Plotting | |
plt.figure(figsize=(8, 5)) | |
plt.scatter(x_vals, y_vals, color='red', label='Data Points') | |
plt.plot(x_vals, linear_fit, label=f'Best Fit: {coeffs[0]:.4f}x + {coeffs[1]:.4f}', color='blue') | |
#plt.plot(x_vals, fx_test, label='f(x) = -2x', color='green', linestyle='--') | |
plt.title('Comparison of Function Fits') | |
plt.xlabel('x') | |
plt.ylabel('f(x)') | |
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
output looks like:
