Chris Parmer — home

Q-Q plot

Statistics — Old Faithful waiting times

Example from the compendium of canonical charts

Statistics — Q-Q plot (Old Faithful waiting times)

Python Code

"""Statistics — Q-Q plot (Old Faithful waiting times)."""
from pathlib import Path

# ── Palette + theme (matching the Plotly Studio gallery these charts ship in) ──
VIOLET, TEAL, GREEN, PINK, ORANGE = "#845EEE", "#52B3D0", "#55B685", "#DA5597", "#E9A23B"
PRIMARY, SECONDARY = VIOLET, TEAL
COLORWAY = [VIOLET, TEAL, GREEN, PINK, ORANGE]
BG, TEXT, GRID, MUTED = "#ffffff", "#1c2024", "#d9d9e0", "#60646c"
FONT = "Inter, -apple-system, BlinkMacSystemFont, sans-serif"
COLORSCALE = [[0, "rgba(132, 94, 238, 0.05)"], [1, "rgba(132, 94, 238, 0.9)"]]


def apply_theme(fig):
    """Light gallery theme: white background, Inter font, soft gridlines."""
    fig.update_layout(
        paper_bgcolor=BG, plot_bgcolor=BG, colorway=COLORWAY,
        font=dict(family=FONT, color=TEXT, size=12),
        legend=dict(font=dict(color=TEXT)),
        hoverlabel=dict(bgcolor="#f0f0f3", font=dict(color=TEXT, family=FONT), bordercolor=GRID),
    )
    fig.update_xaxes(gridcolor=GRID, linecolor=GRID, zerolinecolor=GRID)
    fig.update_yaxes(gridcolor=GRID, linecolor=GRID, zerolinecolor=GRID)


def fetch_csv(url, **kwargs):
    import io
    import pandas as pd
    import requests
    r = requests.get(url, timeout=60)
    r.raise_for_status()
    return pd.read_csv(io.StringIO(r.text), **kwargs)


def fetch_json(url):
    import requests
    r = requests.get(url, timeout=60)
    r.raise_for_status()
    return r.json()

import numpy as np
import plotly.graph_objects as go
from scipy import stats

URL = "https://vincentarelbundock.github.io/Rdatasets/csv/datasets/faithful.csv"


def generate():
    print("fetching Old Faithful data …")
    try:
        df = fetch_csv(URL)
        print(f"  cols: {list(df.columns)}")
        wait_col = next((c for c in df.columns if "wait" in c.lower()), df.columns[-1])
        waiting = df[wait_col].dropna().values
        used_synthetic = False
    except Exception as e:
        print(f"  fetch failed ({e}); generating synthetic bimodal waiting times")
        used_synthetic = True
        rng = np.random.default_rng(42)
        waiting = np.concatenate([
            rng.normal(54, 5, 97),
            rng.normal(80, 6, 175),
        ])

    n = len(waiting)
    sample_q = np.sort(waiting)
    # Theoretical normal quantiles
    prob = (np.arange(1, n + 1) - 0.5) / n
    theoretical_q = stats.norm.ppf(prob)

    # Reference line through Q1 and Q3 of each
    q1_th, q3_th = np.percentile(theoretical_q, [25, 75])
    q1_s,  q3_s  = np.percentile(sample_q,      [25, 75])
    slope = (q3_s - q1_s) / (q3_th - q1_th)
    intercept = q1_s - slope * q1_th

    # Extend reference line across full theoretical range
    x_ref = np.array([theoretical_q.min(), theoretical_q.max()])
    y_ref = slope * x_ref + intercept

    fig = go.Figure([
        go.Scatter(
            x=x_ref,
            y=y_ref,
            mode="lines",
            line=dict(color=TEAL, dash="dash", width=1.8),
            name="Reference line",
            hoverinfo="skip",
        ),
        go.Scatter(
            x=theoretical_q,
            y=sample_q,
            mode="markers",
            marker=dict(color=VIOLET, size=6, opacity=0.7),
            name="Waiting times",
            hovertemplate="theoretical=%{x:.2f}<br>sample=%{y:.1f} min<extra></extra>",
        ),
    ])
    fig.update_layout(
        xaxis=dict(title="Theoretical Quantiles"),
        yaxis=dict(title="Sample Quantiles (minutes)"),
        legend=dict(orientation="h", y=1.05, x=0),
        margin=dict(t=40, b=60, l=70, r=40),
        height=500,
    )
    apply_theme(fig)
    return fig


fig = generate()
fig.show()

Made with Plotly