{"spec_id":"timeseries-forecast-uncertainty","library":"pygal","language":"python","code":"\"\"\" anyplot.ai\ntimeseries-forecast-uncertainty: Time Series Forecast with Uncertainty Band\nLibrary: pygal 3.1.3 | Python 3.14.10\nQuality: 88/100 | Updated: 2026-11-08\n\"\"\"\n\nimport os\nimport sys\nsys.path[:] = [p for p in sys.path if p not in (\"\", \".\", os.path.dirname(__file__))]\n\nimport numpy as np\nimport pandas as pd\nimport pygal\nfrom pygal.style import Style\n\n\nTHEME = os.getenv(\"ANYPLOT_THEME\", \"light\")\nPAGE_BG = \"#FAF8F1\" if THEME == \"light\" else \"#1A1A17\"\nINK = \"#1A1A17\" if THEME == \"light\" else \"#F0EFE8\"\nINK_SOFT = \"#4A4A44\" if THEME == \"light\" else \"#B8B7B0\"\nRULE = \"rgba(26,26,23,0.15)\" if THEME == \"light\" else \"rgba(240,239,232,0.15)\"\n\nBRAND = \"#009E73\"  # historical observations\nFORECAST_COLOR = \"#C475FD\"  # forecast line; its bands are translucent tints of the same lavender\nBAND_95 = \"rgba(196, 117, 253, 0.20)\" if THEME == \"light\" else \"rgba(196, 117, 253, 0.22)\"\nBAND_80 = \"rgba(196, 117, 253, 0.45)\" if THEME == \"light\" else \"rgba(196, 117, 253, 0.42)\"\n\n# Constants\nTICK_COUNT = 7  # about this many date ticks along the x axis\n\n# Columns: set these to your table's column names\nDATE = \"Month\"  # role: date\nACTUAL = \"Monthly sales ($)\"  # role: actual\nFORECAST = \"Forecast\"  # role: forecast\nLOWER_80 = \"Lower 80%\"  # role: lower_80\nUPPER_80 = \"Upper 80%\"  # role: upper_80\nLOWER_95 = \"Lower 95%\"  # role: lower_95\nUPPER_95 = \"Upper 95%\"  # role: upper_95\n\n# Data: replace this block with your own table, for example df = pd.read_csv(\"forecast.csv\")\nnp.random.seed(42)\nmonths = 42\nsplit_idx = 36\n\nt = np.arange(split_idx)\nactual = 1000 + 50 * t + 100 * np.sin(2 * np.pi * t / 12) + np.random.normal(0, 30, split_idx)\n\nt_forecast = np.arange(split_idx, months)\nforecast_values = actual[-1] + 30 * (t_forecast - split_idx) + 50 * np.sin(2 * np.pi * t_forecast / 12)\n\nhistory_gap = np.full(split_idx, np.nan)\nforecast_gap = np.full(months - split_idx, np.nan)\ndf = pd.DataFrame(\n    {\n        DATE: pd.date_range(\"2022-01-01\", periods=months, freq=\"MS\"),\n        ACTUAL: np.concatenate([actual, forecast_gap]),\n        FORECAST: np.concatenate([history_gap, forecast_values]),\n        LOWER_80: np.concatenate([history_gap, forecast_values - 100]),\n        UPPER_80: np.concatenate([history_gap, forecast_values + 100]),\n        LOWER_95: np.concatenate([history_gap, forecast_values - 150]),\n        UPPER_95: np.concatenate([history_gap, forecast_values + 150]),\n    }\n)\n\n# Plot: rows numbered from 1 (no tick at 0, so pygal draws its left spine at the edge)\ndf = df.sort_values(DATE).reset_index(drop=True)\ndf[\"x\"] = np.arange(1, len(df) + 1, dtype=float)\nhist = df[df[ACTUAL].notna()]\nfc = df[df[FORECAST].notna() & df[ACTUAL].isna()]\nbands = fc.dropna(subset=[LOWER_80, UPPER_80, LOWER_95, UPPER_95])\norigin = (float(hist[\"x\"].iloc[-1]), float(hist[ACTUAL].iloc[-1]))  # forecast and bands start at the last observation\n\n# Bands as polygons between their bounds (upper bound forward, lower bound back), starting at the origin:\n# the 80% band, and the two strips of the 95% band outside it, so each colour has exactly one region\nfc_x = [origin[0], *bands[\"x\"]]\nband_80 = list(zip(fc_x, [origin[1], *bands[UPPER_80]], strict=True)) + list(\n    zip(fc_x[::-1], [*bands[LOWER_80][::-1], origin[1]], strict=True)\n)\nband_95_upper = list(zip(fc_x, [origin[1], *bands[UPPER_95]], strict=True)) + list(\n    zip(fc_x[::-1], [*bands[UPPER_80][::-1], origin[1]], strict=True)\n)\nband_95_lower = list(zip(fc_x, [origin[1], *bands[LOWER_80]], strict=True)) + list(\n    zip(fc_x[::-1], [*bands[LOWER_95][::-1], origin[1]], strict=True)\n)\n\n# A 1-2-5 tick step giving about ten y ticks across the data and both 95% bounds\ndata_lo = np.nanmin([df[ACTUAL].min(), df[LOWER_95].min()])\ndata_hi = np.nanmax([df[ACTUAL].max(), df[UPPER_95].max()])\nraw_step = (data_hi - data_lo) / 10\nmagnitude = 10 ** np.floor(np.log10(raw_step))\nSTEP = magnitude * next(m for m in (1, 2, 5, 10) if m * magnitude >= raw_step)\ny_lo = np.floor(data_lo / STEP) * STEP\ny_hi = np.ceil(data_hi / STEP) * STEP + STEP / 2\n# The forecast-start line and its caption are drawn only when the table holds a forecast period\nforecast_start = float(fc[\"x\"].iloc[0]) if len(fc) else None\nmarker = [(forecast_start, y_lo), (forecast_start, y_hi)] if len(fc) else []\ncaption = [{\"value\": (forecast_start + 0.15, y_hi - STEP / 4), \"label\": \"Forecast →\"}] if len(fc) else []\ntick_every = max(1, round(len(df) / TICK_COUNT))\n\nLABEL_FS = 40\ncustom_style = Style(\n    background=PAGE_BG,\n    plot_background=PAGE_BG,\n    foreground=INK,\n    foreground_strong=INK,\n    foreground_subtle=INK_SOFT,\n    colors=(INK, BAND_95, BAND_95, BAND_80, INK_SOFT, BRAND, FORECAST_COLOR),\n    value_colors=(INK,) * 7,\n    opacity=1,\n    opacity_hover=1,\n    stroke_opacity=1,\n    stroke_opacity_hover=1,\n    stroke_width=5,\n    guide_stroke_color=RULE,\n    guide_stroke_dasharray=\"none\",\n    major_guide_stroke_color=RULE,\n    major_guide_stroke_dasharray=\"none\",\n    title_font_size=60,\n    label_font_size=44,\n    major_label_font_size=44,\n    legend_font_size=42,\n    # pygal prints a point's label value_font_size px right of it and 4/3 of that below it;\n    # at 0.26 x the label size the text sits vertically centred on its point\n    value_font_size=round(0.26 * LABEL_FS),\n    value_label_font_size=LABEL_FS,\n    tooltip_font_size=34,\n)\n\nchart = pygal.XY(\n    width=3200,\n    height=1800,\n    style=custom_style,\n    title=\"timeseries-forecast-uncertainty · python · pygal · anyplot.ai\",\n    x_title=DATE,\n    y_title=ACTUAL,\n    show_x_guides=False,\n    show_y_guides=True,\n    show_legend=True,\n    legend_at_bottom=True,\n    legend_at_bottom_columns=5,  # one row; pygal counts the untitled series too when it reserves legend rows\n    legend_box_size=36,\n    truncate_legend=-1,\n    xrange=(float(df[\"x\"].iloc[0]), float(df[\"x\"].iloc[-1]) + 0.5),\n    range=(float(y_lo), float(y_hi)),\n    print_labels=True,\n    print_values=False,\n    margin=40,\n    spacing=24,\n    css=(\n        \"file://style.css\",\n        \"file://graph.css\",\n        \"inline:.serie-1 .line, .serie-2 .line, .serie-3 .line { stroke-width: 0 !important; }\",\n        \"inline:.serie-4 .line { stroke-width: 3px !important; }\",\n        \"inline:.text-overlay text.label { font-weight: bold; }\",\n        \"inline:.plot_title { font-weight: bold; }\",\n        # pygal sets legend text only 5 px right of its swatch; push it clear of the box\n        \"inline:.legends .legend text { transform: translate(14px, 0px); }\",\n        # The dashed series get dashed outline swatches instead of solid squares\n        \"inline:#activate-serie-4 rect, #activate-serie-6 rect \"\n        \"{ fill: none !important; stroke-width: 5px; stroke-dasharray: 9, 5; }\",\n        f\"inline:#activate-serie-4 rect {{ stroke: {INK_SOFT} !important; }}\",\n        f\"inline:#activate-serie-6 rect {{ stroke: {FORECAST_COLOR} !important; }}\",\n    ),\n)\nchart.x_labels = [\n    {\"value\": int(row[\"x\"]), \"label\": row[DATE].strftime(\"%b %y\")} for _, row in df.iloc[::tick_every].iterrows()\n]\n\n# Label first and bands next, so the lines are drawn on top of the fills\nchart.add(None, caption, stroke=False, dots_size=0)\nchart.add(\"95% interval\", band_95_upper, fill=True, show_dots=False)\nchart.add(None, band_95_lower, fill=True, show_dots=False)\nchart.add(\"80% interval\", band_80, fill=True, show_dots=False)\nchart.add(\"Forecast start\", marker, show_dots=False, stroke_style={\"dasharray\": \"14, 10\"})\nchart.add(\n    \"Observed history\",\n    list(zip(hist[\"x\"], hist[ACTUAL], strict=True)),\n    dots_size=5,\n    formatter=lambda p: f\"${p[1]:,.0f}\",\n)\nchart.add(\n    FORECAST,\n    [origin, *zip(fc[\"x\"], fc[FORECAST], strict=True)],\n    dots_size=5,\n    stroke_style={\"dasharray\": \"22, 12\"},\n    formatter=lambda p: f\"${p[1]:,.0f}\",\n)\n\n# Save\nchart.render_to_png(f\"plot-{THEME}.png\")\nwith open(f\"plot-{THEME}.html\", \"wb\") as f:\n    f.write(chart.render())\n"}