Sure! If you're trying to fit a horizontal line with an offset, this is essentially fitting a model of the form:
y=c
Where c is the constant (offset) value you're trying to find. This model has only one degree of freedom — the vertical offset.
You can do this in Python using libraries like NumPy or SciPy. Here's a simple example using numpy and matplotlib for visualization.
✅ Example Code: Fitting a Horizontal Line (Constant Value)
import numpy as np
import matplotlib.pyplot as plt
# Sample dataset: replace these with your actual data
x = np.linspace(0, 10, 50)
y = np.sin(x) + 2.5 + np.random.normal(0, 0.2, size=x.shape) # some noisy data around y ~ 2.5
# Fit a horizontal line (constant value)
# Since we are fitting y = c, just take the mean of y values
c_fit = np.mean(y)
# Generate fitted y values
y_fit = np.full_like(x, c_fit)
# Plotting
plt.figure(figsize=(8, 5))
plt.scatter(x, y, label='Data', color='blue')
plt.plot(x, y_fit, 'r-', label=f'Fit: y = {c_fit:.2f}')
plt.axhline(c_fit, color='green', linestyle='--', alpha=0.6, label='Offset line')
plt.legend()
plt.xlabel('x')
plt.ylabel('y')
plt.title('Fitting a Horizontal Line with Offset')
plt.grid(True)
plt.show()
# Print result
print(f"Best-fit constant offset: {c_fit:.3f}")
🔍 Explanation:
- We assume that the best horizontal line through the data is simply the mean of the
y values.
- This minimizes the sum of squared residuals (i.e., ordinary least squares).
- No optimization library is needed because it’s a simple analytical solution.
If you want to use an optimization function (e.g., for learning purposes), here's how you could use scipy.optimize.curve_fit:
🧪 Optional: Using curve_fit from SciPy
from scipy.optimize import curve_fit
# Define the horizontal line model
def horizontal_line(x, c):
return np.full_like(x, c)
# Perform the fit
popt, pcov = curve_fit(horizontal_line, x, y)
c_fit_scipy = popt[0]
# Plotting
plt.figure(figsize=(8, 5))
plt.scatter(x, y, label='Data', color='blue')
plt.plot(x, horizontal_line(x, c_fit_scipy), 'r-', label=f'Fit: y = {c_fit_scipy:.2f}')
plt.legend()
plt.xlabel('x')
plt.ylabel('y')
plt.title('Fitting a Horizontal Line with Offset (Using curve_fit)')
plt.grid(True)
plt.show()
print(f"Best-fit constant offset (SciPy): {c_fit_scipy:.3f}")
Both approaches will give you a good estimate of the best horizontal line (with only one parameter to fit: the offset).
Let me know if your data has special constraints or weighting needs!