website/examples/gallery/scatter-1.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,
        },
    )
)


from random import Random
from statistics import median


def load_data():
    rng = Random(21)
    return [
        (
            controller,
            round(minutes := rng.uniform(10, 17) - 3 * index, 1),
            round(minutes * 0.42 + rng.uniform(-0.2, 0.2), 1),
        )
        for index, controller in enumerate(("Original", "Replacement"))
        for _ in range(260)
    ]


def make_before(data):
    fig = go.Figure()
    for controller in ("Replacement", "Original"):
        energy = [kwh for group, _, kwh in data if group == controller]
        fig.add_scatter(
            x=energy,
            y=[int(controller == "Original")] * len(energy),
            mode="markers",
            name=controller,
            marker=dict(size=10, color=INK),
        )
    fig.update_layout(
        template="warm_editorial",
        title="Pump energy by controller",
        xaxis_title="Energy per cycle (kWh)",
        yaxis=dict(tickvals=[0, 1], ticktext=["Replacement", "Original"]),
        xaxis_range=[0, 15],
        legend=dict(x=0.46, y=0.6),
    )
    return fig


def make_after(data):
    from plotly.subplots import make_subplots

    fig = make_subplots(rows=2, cols=1, vertical_spacing=0.30)
    for row, column, label in [
        (1, 2, "Electricity per cycle (kWh)"),
        (2, 1, "Motor runtime per cycle (min)"),
    ]:
        for group in ("Original", "Replacement"):
            values = [record[column] for record in data if record[0] == group]
            fig.add_scatter(
                x=values,
                y=[group] * len(values),
                mode="markers",
                row=row,
                col=1,
                marker=dict(size=5, color=MUTED, opacity=0.12),
                showlegend=False,
            )
            fig.add_scatter(
                x=[median(values)],
                y=[group],
                mode="markers",
                row=row,
                col=1,
                marker=dict(size=11, color=WARM_EDITORIAL_PALETTE[0], symbol="diamond"),
                showlegend=False,
            )
        values = [record[column] for record in data]
        fig.update_xaxes(
            title_text=label,
            tickvals=[min(values), round(median(values), 1), max(values)],
            range=[min(values) - 0.25, max(values) + 0.25],
            row=row,
            col=1,
        )
    fig.update_layout(
        template="warm_editorial",
        title="Shorter pump cycles use less electricity",
        margin=dict(l=100, r=24, t=72, b=45),
    )
    fig.add_annotation(
        text="Diamonds mark medians",
        x=1,
        y=1.13,
        xref="paper",
        yref="paper",
        xanchor="right",
        showarrow=False,
    )
    return fig


EXAMPLE = {
    "kind": "scatter",
    "source": "Illustrative pump bench trial with 260 cycles per controller at constant load.",
    "before": {"summary": "Cycle energy overlaps between the two controller settings."},
    "after": {
        "summary": "The replacement runs the motor for less time and draws less energy per cycle."
    },
    "principles": {
        "cleveland-dot-plot": {
            "question": "Which controller typically uses less electricity?",
            "book": {
                "quote": "A dot plot encodes values by position along a common scale without needing to include zero when all observations lie in a narrow band",
                "page": 150,
            },
            "before": {
                "caption": "Each controller occupies a thick stripe without a marked center."
            },
            "after": {
                "caption": "Median diamonds rank the two controllers on one horizontal energy scale."
            },
        },
        "range-frame": {
            "question": "What range of readings did the trial cover?",
            "book": {"quote": "an effective data-communicating element", "page": 132, "line": 5156},
            "before": {"caption": "The energy scale extends to 15 kWh, well beyond either group."},
            "after": {
                "caption": "The first and last labeled ticks give the observed extremes for each measure."
            },
        },
        "overplotted-scatter": {
            "question": "Where do most cycles fall?",
            "book": {
                "quote": "Making individual points partially transparent lets dense regions appear darker while sparse areas stay light",
                "page": 219,
            },
            "before": {"caption": "Opaque dots cover earlier readings at the same energy level."},
            "after": {"caption": "Translucent cycle marks darken where many readings coincide."},
        },
        "place-and-fit-legends": {
            "question": "Which marks belong to the replacement?",
            "book": {"quote": "arranged in the order of the corresponding bars,", "page": 246},
            "before": {"caption": "A redundant key sits inside the plotting area."},
            "after": {
                "caption": "Row labels identify the controllers and a single note identifies both median diamonds."
            },
        },
        "evidence-for-causal-mechanism": {
            "question": "What changed inside the pump cycle?",
            "book": {
                "quote": "the representation of mechanism and motion, of process and dynamics, of causes and effects",
                "page": 10,
            },
            "before": {"caption": "Energy readings alone give no evidence about motor runtime."},
            "after": {
                "caption": "The aligned runtime rows show the shorter cycles behind the lower energy use."
            },
        },
    },
}