{"spec_id":"timeseries-decomposition","library":"bokeh","language":"python","code":"\"\"\" anyplot.ai\ntimeseries-decomposition: Time Series Decomposition Plot\nLibrary: bokeh 3.9.0 | Python 3.13.13\nQuality: 86/100 | Updated: 2026-05-14\n\"\"\"\n\nimport os\nimport time\nfrom pathlib import Path\n\nimport numpy as np\nimport pandas as pd\nfrom bokeh.io import output_file, save\nfrom bokeh.layouts import column\nfrom bokeh.models import ColumnDataSource\nfrom bokeh.plotting import figure\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\nfrom statsmodels.tsa.seasonal import seasonal_decompose\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\"\n\n# Okabe-Ito palette for visual distinction of components\nIMPRINT = [\"#009E73\", \"#C475FD\", \"#4467A3\", \"#BD8233\"]  # Positions 1-4\n\n# Data - Monthly airline passengers (classic time series dataset)\nnp.random.seed(42)\ndate_range = pd.date_range(start=\"2018-01-01\", periods=120, freq=\"MS\")  # 10 years monthly\n\n# Generate realistic airline passenger data with trend, seasonality, and noise\ntrend = np.linspace(100, 250, 120)  # Upward trend in thousands of passengers\nseasonal_pattern = 30 * np.sin(2 * np.pi * np.arange(120) / 12)  # Annual seasonality\nnoise = np.random.normal(0, 10, 120)\npassengers = trend + seasonal_pattern + noise\n\n# Create DataFrame and perform decomposition\ndf = pd.DataFrame({\"date\": date_range, \"passengers\": passengers})\ndf.set_index(\"date\", inplace=True)\ndecomposition = seasonal_decompose(df[\"passengers\"], model=\"additive\", period=12)\n\n# Extract components\ndates = df.index.to_list()\noriginal = df[\"passengers\"].values\ntrend_component = decomposition.trend.values\nseasonal_component = decomposition.seasonal.values\nresidual_component = decomposition.resid.values\n\n# Panel dimensions (4 panels in vertical layout)\npanel_height = 650\ntotal_width = 4800\n\n\n# Helper function to create themed figure\ndef create_themed_figure(width, height, title_text, y_label, show_x_axis=False, x_range=None):\n    kwargs = {\n        \"width\": width,\n        \"height\": height,\n        \"x_axis_type\": \"datetime\",\n        \"title\": title_text,\n        \"toolbar_location\": None,  # Hide toolbar for cleaner look\n    }\n    if x_range is not None:\n        kwargs[\"x_range\"] = x_range\n\n    p = figure(**kwargs)\n\n    # Theme-adaptive styling\n    p.background_fill_color = PAGE_BG\n    p.border_fill_color = PAGE_BG\n    p.outline_line_color = INK_SOFT\n\n    p.title.text_color = INK\n    p.title.text_font_size = \"26pt\"\n    p.title.text_font_style = \"bold\"\n\n    p.xaxis.axis_label_text_color = INK\n    p.yaxis.axis_label_text_color = INK\n    p.xaxis.axis_label_text_font_size = \"20pt\"\n    p.yaxis.axis_label_text_font_size = \"20pt\"\n\n    p.xaxis.major_label_text_color = INK_SOFT\n    p.yaxis.major_label_text_color = INK_SOFT\n    p.xaxis.major_label_text_font_size = \"16pt\"\n    p.yaxis.major_label_text_font_size = \"16pt\"\n\n    p.xaxis.axis_line_color = INK_SOFT\n    p.yaxis.axis_line_color = INK_SOFT\n    p.xaxis.major_tick_line_color = INK_SOFT\n    p.yaxis.major_tick_line_color = INK_SOFT\n\n    p.ygrid.grid_line_color = INK\n    p.ygrid.grid_line_alpha = 0.12\n    p.xgrid.grid_line_color = INK\n    p.xgrid.grid_line_alpha = 0.08\n\n    p.yaxis.axis_label = y_label\n    if not show_x_axis:\n        p.xaxis.visible = False\n    else:\n        p.xaxis.axis_label = \"Date\"\n\n    p.min_border_left = 100\n    p.min_border_right = 40\n    p.min_border_top = 60\n    p.min_border_bottom = 60\n\n    return p\n\n\n# Create subplots with theme-aware styling and distinct colors\np1 = create_themed_figure(total_width, panel_height, \"Original Series\", \"Passengers (thousands)\")\nsource1 = ColumnDataSource(data={\"date\": dates, \"value\": original})\np1.line(\"date\", \"value\", source=source1, line_width=3, color=IMPRINT[0])\n\np2 = create_themed_figure(total_width, panel_height, \"Trend Component\", \"Trend\", x_range=p1.x_range)\nsource2 = ColumnDataSource(data={\"date\": dates, \"value\": trend_component})\np2.line(\"date\", \"value\", source=source2, line_width=3, color=IMPRINT[1])\n\np3 = create_themed_figure(total_width, panel_height, \"Seasonal Component\", \"Seasonal\", x_range=p1.x_range)\nsource3 = ColumnDataSource(data={\"date\": dates, \"value\": seasonal_component})\np3.line(\"date\", \"value\", source=source3, line_width=3, color=IMPRINT[2])\n\np4 = create_themed_figure(\n    total_width, panel_height, \"Residual Component\", \"Residual\", show_x_axis=True, x_range=p1.x_range\n)\nsource4 = ColumnDataSource(data={\"date\": dates, \"value\": residual_component})\np4.line(\"date\", \"value\", source=source4, line_width=3, color=IMPRINT[3])\n\n# Combine all panels into vertical layout\nlayout = column(p1, p2, p3, p4)\n\n# Save interactive HTML\noutput_file(f\"plot-{THEME}.html\")\nsave(layout)\n\n# Screenshot with headless Chrome using Selenium\nW, H = 4800, 2700\nopts = Options()\nfor arg in (\n    \"--headless=new\",\n    \"--no-sandbox\",\n    \"--disable-dev-shm-usage\",\n    \"--disable-gpu\",\n    f\"--window-size={W},{H}\",\n    \"--hide-scrollbars\",\n):\n    opts.add_argument(arg)\n\ndriver = webdriver.Chrome(options=opts)\ndriver.set_window_size(W, H)\ndriver.get(f\"file://{Path(f'plot-{THEME}.html').resolve()}\")\ntime.sleep(3)  # Let bokeh's JS render the canvas\ndriver.save_screenshot(f\"plot-{THEME}.png\")\ndriver.quit()\n"}