website/examples/gallery/histogram-2.py

import plotly.graph_objects as go
import plotly.io as pio

INK = "#1C1917"
MUTED = "#57534E"
WARM_EDITORIAL_PALETTE = [
    "#0F766E",
    "#C2410C",
    "#1D4ED8",
    "#A16207",
    "#7E22CE",
    "#475569",
    "#0369A1",
    "#1C1917",
]
CANVAS = "#FFF7ED"
RULE = "#E7DDD2"

pio.templates["warm_editorial"] = go.layout.Template(
    layout=go.Layout(
        colorway=WARM_EDITORIAL_PALETTE,
        font={"family": "Inter, system-ui, -apple-system, sans-serif", "size": 13, "color": INK},
        title={
            "x": 0,
            "xanchor": "left",
            "font": {"family": "Georgia, 'Times New Roman', serif", "size": 18, "color": INK},
        },
        paper_bgcolor=CANVAS,
        plot_bgcolor=CANVAS,
        xaxis={
            "showgrid": False,
            "showline": True,
            "linecolor": "#A8A29E",
            "tickcolor": "#A8A29E",
            "tickfont": {"color": MUTED},
            "automargin": True,
        },
        yaxis={
            "showgrid": True,
            "gridcolor": RULE,
            "gridwidth": 1,
            "showline": False,
            "tickcolor": "#A8A29E",
            "tickfont": {"color": MUTED},
            "zeroline": False,
            "automargin": True,
        },
    )
)


import numpy as np
from plotly.subplots import make_subplots


def load_data():
    rng = np.random.default_rng(23)
    return {
        shift: sorted(np.round(rng.lognormal(center, 0.35, size), 1).tolist())
        for shift, center, size in [("Morning", 2.0, 80), ("Evening", 2.4, 120)]
    }


def make_before(data):
    edges = [0, 5, 10, 20, 40]
    pooled = data["Morning"] + data["Evening"]
    counts, _ = np.histogram(pooled, bins=edges)
    fig = go.Figure(
        go.Bar(x=[2.5, 7.5, 15, 30], width=[5, 5, 10, 20], y=counts.tolist(), marker_color=MUTED)
    )
    fig.update_layout(
        template="warm_editorial",
        title="Service duration across both shifts",
        xaxis_title="Minutes",
        yaxis_title="Calls",
    )
    return fig


def make_after(data):
    fig = make_subplots(
        rows=2, cols=1, shared_xaxes=True, row_heights=[0.7, 0.3], vertical_spacing=0.16
    )
    for (shift, values), color, dash in zip(
        data.items(), (MUTED, WARM_EDITORIAL_PALETTE[0]), ("dot", "solid"), strict=True
    ):
        fig.add_scatter(
            x=[0] + values,
            y=[0] + [(i + 1) / len(values) for i in range(len(values))],
            mode="lines",
            name=shift,
            line=dict(shape="hv", color=color, dash=dash),
            row=1,
            col=1,
        )
        fig.add_annotation(x=values[-1], y=1, text=shift, showarrow=False, yshift=11, row=1, col=1)
        quantiles = np.quantile(values, (np.arange(10) + 0.5) / 10)
        fig.add_scatter(
            x=quantiles.tolist(),
            y=[shift] * 10,
            mode="markers",
            showlegend=False,
            marker=dict(color=color, size=8, symbol="diamond-open"),
            row=2,
            col=1,
        )
    fig.add_hline(y=0.9, line_color=INK, line_dash="dash", row=1, col=1)
    fig.update_xaxes(title_text="Call duration (minutes)", row=2, col=1)
    fig.update_yaxes(title_text="Share completed", tickformat=".0%", row=1, col=1)
    fig.update_layout(
        template="warm_editorial",
        title="Evening calls take longer at matched percentiles",
        title_subtitle_text="Each diamond represents one tenth of a shift's calls.",
        showlegend=False,
        yaxis_range=[-0.03, 1.14],
        margin=dict(t=95, b=55),
    )
    return fig


EXAMPLE = {
    "kind": "histogram",
    "source": "Illustrative call logs with 80 morning calls and 120 evening calls.",
    "before": {"summary": "Pooled counts are drawn in intervals of unequal width."},
    "after": {"summary": "At the same cumulative share, evening calls generally take longer."},
    "principles": {
        "multivariate": {
            "question": "Does the shift change the distribution of call times?",
            "book": {
                "quote": "Graphical excellence is nearly always multivariate",
                "page": 55,
                "line": 1354,
            },
            "before": {"caption": "Pooling calls erases the shift recorded for each duration."},
            "after": {
                "caption": "Named step curves and matching rows keep both shift and duration visible."
            },
        },
        "ecdf-and-qq-plots": {
            "question": "What share of calls finished within a given time?",
            "book": {
                "quote": "Empirical cumulative distribution functions display all data points directly without arbitrary bin width or bandwidth parameters",
                "page": 71,
            },
            "before": {"caption": "Intervals hide the exact cumulative share below a deadline."},
            "after": {
                "caption": "Each step gives the fraction finished by the minute on the horizontal axis."
            },
        },
        "histogram-density-mass": {
            "question": "How much probability falls between two times?",
            "book": {"quote": "area under the curve equals 1.", "page": 62},
            "before": {"caption": "Wide bins give the same count more ink than narrow bins."},
            "after": {
                "caption": "The rise in cumulative share gives interval probability directly."
            },
        },
        "matched-quantile-coordinates": {
            "question": "How do the slowest calls compare at the same rank?",
            "book": {"quote": "typically must be computed by interpolation.", "page": 144},
            "before": {"caption": "Pooled counts erase percentile ranks in the unequal samples."},
            "after": {
                "caption": "The horizontal 90 percent guide intersects both curves at the same cumulative probability."
            },
        },
        "quantile-dotplot": {
            "question": "How common are long calls within each shift?",
            "book": {
                "quote": "Discretizing a probability distribution into countable outcomes lets readers judge tail risk by counting dots",
                "page": 184,
            },
            "before": {
                "caption": "The pooled histogram cannot express a tail as a count out of ten."
            },
            "after": {
                "caption": "Ten equally weighted quantile diamonds per row turn the tail into an approximate frequency."
            },
        },
    },
}