{"spec_id":"timeseries-decomposition","library":"seaborn","language":"python","code":"\"\"\" anyplot.ai\ntimeseries-decomposition: Time Series Decomposition Plot\nLibrary: seaborn 0.13.2 | Python 3.13.13\nQuality: 97/100 | Updated: 2026-05-14\n\"\"\"\n\nimport os\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\n\n\n# Theme tokens\nTHEME = os.getenv(\"ANYPLOT_THEME\", \"light\")\nPAGE_BG = \"#FAF8F1\" if THEME == \"light\" else \"#1A1A17\"\nELEVATED_BG = \"#FFFDF6\" if THEME == \"light\" else \"#242420\"\nINK = \"#1A1A17\" if THEME == \"light\" else \"#F0EFE8\"\nINK_SOFT = \"#4A4A44\" if THEME == \"light\" else \"#B8B7B0\"\nINK_MUTED = \"#6B6A63\" if THEME == \"light\" else \"#A8A79F\"\nRULE = \"rgba(26,26,23,0.10)\" if THEME == \"light\" else \"rgba(240,239,232,0.10)\"\n\nBRAND = \"#009E73\"\nCOLOR_TREND = \"#C475FD\"\nCOLOR_SEASONAL = \"#4467A3\"\nCOLOR_RESIDUAL = \"#BD8233\"\n\n# Set seaborn theme with theme-adaptive colors\nsns.set_theme(\n    style=\"ticks\",\n    rc={\n        \"figure.facecolor\": PAGE_BG,\n        \"axes.facecolor\": PAGE_BG,\n        \"axes.edgecolor\": INK_SOFT,\n        \"axes.labelcolor\": INK,\n        \"text.color\": INK,\n        \"xtick.color\": INK_SOFT,\n        \"ytick.color\": INK_SOFT,\n        \"grid.color\": INK,\n        \"grid.alpha\": 0.10,\n        \"legend.facecolor\": ELEVATED_BG,\n        \"legend.edgecolor\": INK_SOFT,\n    },\n)\n\n# Data - Monthly electricity consumption (kWh)\nnp.random.seed(42)\nn_years = 8\nn_months = n_years * 12\nperiod = 12\n\n# Create date range\ndates = pd.date_range(start=\"2016-01-01\", periods=n_months, freq=\"MS\")\n\n# Generate realistic electricity consumption with trend, seasonality, and noise\n# Trend: growing demand over years (5000 to 7500 kWh)\ntrend_component = np.linspace(5000, 7500, n_months)\n\n# Seasonality: higher in summer/winter (AC/heating), lower in spring/fall\nseasonal_pattern = np.array([1.25, 1.20, 1.05, 0.95, 0.85, 0.90, 1.10, 1.15, 1.05, 0.95, 1.10, 1.20])\nseasonal_component = np.tile(seasonal_pattern, n_years)\n\n# Noise\nnoise = np.random.normal(0, 100, n_months)\n\n# Multiplicative model\nvalues = trend_component * seasonal_component + noise\n\n# Create DataFrame\ndf = pd.DataFrame({\"date\": dates, \"consumption\": values})\ndf = df.set_index(\"date\")\n\n# Manual seasonal decomposition (additive model)\ntrend = df[\"consumption\"].rolling(window=period, center=True, min_periods=1).mean()\ndetrended = df[\"consumption\"] - trend\nseasonal = detrended.groupby(detrended.index.month).transform(\"mean\")\nresidual = df[\"consumption\"] - trend - seasonal\n\n# Create figure with 4 subplots\nfig, axes = plt.subplots(4, 1, figsize=(16, 9), sharex=True)\nfig.patch.set_facecolor(PAGE_BG)\nfor ax in axes:\n    ax.set_facecolor(PAGE_BG)\n\nfig.subplots_adjust(hspace=0.25)\n\n# Plot 1: Original\nsns.lineplot(x=df.index, y=df[\"consumption\"], ax=axes[0], color=BRAND, linewidth=2.5, legend=False)\naxes[0].set_ylabel(\"Original (kWh)\", fontsize=20, color=INK)\naxes[0].set_title(\"Original\", fontsize=22, fontweight=\"medium\", loc=\"left\", color=INK)\naxes[0].tick_params(axis=\"both\", labelsize=16, colors=INK_SOFT)\naxes[0].grid(True, alpha=0.1, linewidth=0.8)\naxes[0].spines[\"top\"].set_visible(False)\naxes[0].spines[\"right\"].set_visible(False)\nfor spine in (\"left\", \"bottom\"):\n    axes[0].spines[spine].set_color(INK_SOFT)\n\n# Plot 2: Trend\nsns.lineplot(x=trend.index, y=trend.values, ax=axes[1], color=COLOR_TREND, linewidth=2.5, legend=False)\naxes[1].set_ylabel(\"Trend (kWh)\", fontsize=20, color=INK)\naxes[1].set_title(\"Trend\", fontsize=22, fontweight=\"medium\", loc=\"left\", color=INK)\naxes[1].tick_params(axis=\"both\", labelsize=16, colors=INK_SOFT)\naxes[1].grid(True, alpha=0.1, linewidth=0.8)\naxes[1].spines[\"top\"].set_visible(False)\naxes[1].spines[\"right\"].set_visible(False)\nfor spine in (\"left\", \"bottom\"):\n    axes[1].spines[spine].set_color(INK_SOFT)\n\n# Plot 3: Seasonal\nsns.lineplot(x=seasonal.index, y=seasonal.values, ax=axes[2], color=COLOR_SEASONAL, linewidth=2.5, legend=False)\naxes[2].axhline(y=0, color=INK_SOFT, linestyle=\"--\", linewidth=1, alpha=0.5)\naxes[2].set_ylabel(\"Seasonal (kWh)\", fontsize=20, color=INK)\naxes[2].set_title(\"Seasonal\", fontsize=22, fontweight=\"medium\", loc=\"left\", color=INK)\naxes[2].tick_params(axis=\"both\", labelsize=16, colors=INK_SOFT)\naxes[2].grid(True, alpha=0.1, linewidth=0.8)\naxes[2].spines[\"top\"].set_visible(False)\naxes[2].spines[\"right\"].set_visible(False)\nfor spine in (\"left\", \"bottom\"):\n    axes[2].spines[spine].set_color(INK_SOFT)\n\n# Plot 4: Residual\nsns.lineplot(x=residual.index, y=residual.values, ax=axes[3], color=COLOR_RESIDUAL, linewidth=2.0, legend=False)\naxes[3].axhline(y=0, color=INK_SOFT, linestyle=\"--\", linewidth=1, alpha=0.5)\naxes[3].set_ylabel(\"Residual (kWh)\", fontsize=20, color=INK)\naxes[3].set_xlabel(\"Date\", fontsize=20, color=INK)\naxes[3].set_title(\"Residual\", fontsize=22, fontweight=\"medium\", loc=\"left\", color=INK)\naxes[3].tick_params(axis=\"both\", labelsize=16, colors=INK_SOFT)\naxes[3].grid(True, alpha=0.1, linewidth=0.8)\naxes[3].spines[\"top\"].set_visible(False)\naxes[3].spines[\"right\"].set_visible(False)\nfor spine in (\"left\", \"bottom\"):\n    axes[3].spines[spine].set_color(INK_SOFT)\n\n# Main title\nfig.suptitle(\"timeseries-decomposition · seaborn · anyplot.ai\", fontsize=24, fontweight=\"medium\", y=0.995, color=INK)\n\nplt.tight_layout(rect=[0, 0, 1, 0.99])\nplt.savefig(f\"plot-{THEME}.png\", dpi=300, bbox_inches=\"tight\", facecolor=PAGE_BG)\n"}