{"spec_id":"residual-plot","library":"matplotlib","language":"python","code":"\"\"\" anyplot.ai\nresidual-plot: Residual Plot\nLibrary: matplotlib 3.10.9 | Python 3.13.13\nQuality: 84/100 | Updated: 2026-05-10\n\"\"\"\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\n# Data - Generate realistic regression scenario\nnp.random.seed(42)\n\n# Independent variable with some structure\nX = np.linspace(0, 10, 150)\n\n# True relationship with some non-linearity to make residuals interesting\n# (quadratic component makes linear model show patterns in residuals)\ny_true = 2.5 * X + 0.3 * X**2 + np.random.randn(150) * 3\n\n# Fit linear regression manually: y = a + b*x\n# Using least squares formulas\nx_mean = np.mean(X)\ny_mean = np.mean(y_true)\nb = np.sum((X - x_mean) * (y_true - y_mean)) / np.sum((X - x_mean) ** 2)\na = y_mean - b * x_mean\ny_pred = a + b * X\n\n# Calculate residuals\nresiduals = y_true - y_pred\n\n# Identify outliers (beyond 2 standard deviations)\nstd_residuals = np.std(residuals)\noutlier_mask = np.abs(residuals) > 2 * std_residuals\n\n# Create plot\nfig, ax = plt.subplots(figsize=(16, 9))\n\n# Plot normal points\nax.scatter(\n    y_pred[~outlier_mask],\n    residuals[~outlier_mask],\n    s=150,\n    alpha=0.7,\n    color=\"#306998\",\n    edgecolors=\"white\",\n    linewidth=0.5,\n    label=\"Residuals\",\n)\n\n# Plot outliers with different color\nax.scatter(\n    y_pred[outlier_mask],\n    residuals[outlier_mask],\n    s=180,\n    alpha=0.9,\n    color=\"#FFD43B\",\n    edgecolors=\"#306998\",\n    linewidth=1.5,\n    label=\"Outliers (>2σ)\",\n)\n\n# Reference line at y=0\nax.axhline(y=0, color=\"#333333\", linewidth=2, linestyle=\"-\", label=\"Perfect fit (y=0)\")\n\n# Add ±2 standard deviation bands\nax.axhline(y=2 * std_residuals, color=\"#888888\", linewidth=1.5, linestyle=\"--\", alpha=0.7)\nax.axhline(y=-2 * std_residuals, color=\"#888888\", linewidth=1.5, linestyle=\"--\", alpha=0.7)\n\n# Get x limits for the band\nxlim = (y_pred.min() - 2, y_pred.max() + 2)\nax.fill_between(xlim, -2 * std_residuals, 2 * std_residuals, alpha=0.1, color=\"#306998\", label=\"±2σ band\")\n\n# Add trend line using polynomial fit to detect patterns\nz = np.polyfit(y_pred, residuals, 3)\np = np.poly1d(z)\nx_smooth = np.linspace(y_pred.min(), y_pred.max(), 100)\nax.plot(x_smooth, p(x_smooth), color=\"#D62728\", linewidth=2.5, linestyle=\"-\", alpha=0.8, label=\"Trend line\")\n\n# Labels and styling\nax.set_xlabel(\"Fitted Values\", fontsize=20)\nax.set_ylabel(\"Residuals (Observed - Predicted)\", fontsize=20)\nax.set_title(\"residual-plot · matplotlib · pyplots.ai\", fontsize=24)\nax.tick_params(axis=\"both\", labelsize=16)\nax.legend(fontsize=14, loc=\"upper left\", framealpha=0.9)\nax.grid(True, alpha=0.3, linestyle=\"--\")\nax.set_xlim(xlim)\n\nplt.tight_layout()\nplt.savefig(\"plot.png\", dpi=300, bbox_inches=\"tight\")\n"}