Line & Scatter

Linear Regression Fit

Scatter plot with fitted regression line and equation.

Output
Linear Regression Fit
Python
import matplotlib.pyplot as plt
import numpy as np

# === STYLE CONFIG ===
COLORS = {
    'points': '#8B5CF6',     # Violet
    'line': '#F43F5E',       # Rose
    'background': '#FAFBFC',
    'text_muted': '#64748B',
    'grid': '#E2E8F0',
}

# === DATA ===
np.random.seed(42)
x = np.linspace(0, 10, 50)
y = 1.5 * x + 2 + np.random.normal(0, 1.5, 50)

# Fit line
coeffs = np.polyfit(x, y, 1)
fit_line = np.poly1d(coeffs)
r_squared = 1 - np.sum((y - fit_line(x))**2) / np.sum((y - np.mean(y))**2)

# === FIGURE ===
fig, ax = plt.subplots(figsize=(10, 6), dpi=100)
ax.set_facecolor(COLORS['background'])
fig.patch.set_facecolor(COLORS['background'])

# === PLOT ===
ax.scatter(x, y, color=COLORS['points'], s=50, alpha=0.7,
           edgecolors='white', linewidths=1.5, label='Data', zorder=2)

ax.plot(x, fit_line(x), color=COLORS['line'], linewidth=2.5,
        label=f'Fit: y = {coeffs[0]:.2f}x + {coeffs[1]:.2f}', zorder=3)

# R² annotation
ax.text(0.95, 0.05, f'R² = {r_squared:.3f}', transform=ax.transAxes,
        fontsize=10, color=COLORS['text_muted'], ha='right',
        bbox=dict(boxstyle='round,pad=0.3', facecolor='white', edgecolor=COLORS['grid']))

# === AXES ===
ax.set_xlim(-0.5, 11)
ax.set_ylim(-2, 20)
ax.set_xlabel('X', fontsize=10, color=COLORS['text_muted'], labelpad=10)
ax.set_ylabel('Y', fontsize=10, color=COLORS['text_muted'], labelpad=10)

# === STYLING ===
for spine in ['top', 'right']:
    ax.spines[spine].set_visible(False)
for spine in ['bottom', 'left']:
    ax.spines[spine].set_color(COLORS['grid'])

ax.yaxis.grid(True, color=COLORS['grid'], linewidth=0.5, alpha=0.7)
ax.xaxis.grid(False)
ax.set_axisbelow(True)
ax.tick_params(axis='both', colors=COLORS['text_muted'], labelsize=9, length=0, pad=8)

ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.12),
          ncol=2, frameon=False, fontsize=9, labelcolor=COLORS['text_muted'])

plt.tight_layout()
plt.show()
Library

Matplotlib

Category

Pairwise Data

Did this help you?

Support PyLucid to keep it free & growing

Support