Skip to content

Callout Line Plot

A single line of pre-aggregated data with events called out on it.

plot(df, value_col, callouts, callout_title_col=None, callout_text_col=None, x_col=None, callout_x_col=None, title=None, eyebrow=None, subtitle=None, x_label=None, y_label=None, source_text=None, ax=None, figsize=None, show_markers=True, **kwargs)

Plot value_col as one line and call out the events in callouts on it.

Each row of callouts becomes a bold title, wrapped text or both, joined by a leader to the line at that row's x value. An x value between two rows of df is anchored on the straight segment joining them. No callout text touches the line, another callout or a leader, and the y-axis is given extra headroom when the callouts need the room.

df is not aggregated: pass one row per x value. The layout fits the figure's size and the axis limits at call time, so pass figsize (or an ax on a figure already at its final size) instead of resizing the figure afterwards, and do not change the limits afterwards. That rules out an ax whose y-axis is shared with a chart drawn later, and a second call on the same ax.

Parameters:

Name Type Description Default
df DataFrame

The line's data, one row per x value.

required
value_col str

The column to plot.

required
callouts DataFrame

One row per callout.

required
callout_title_col str

The callouts column holding each callout's bold title, such as the event's date already formatted for display.

None
callout_text_col str

The callouts column holding each callout's text, drawn under the title when both are given. At least one of the two is required.

None
x_col str

The column to use as the x-axis, datetime or numeric. If None, the index is used.

None
callout_x_col str

The callouts column holding each callout's x value, of the same type as the line's x values. Defaults to x_col; required when x_col is None.

None
title str

The title of the plot.

None
eyebrow str

Small uppercase label rendered above the title.

None
subtitle str

Supporting copy rendered below the title.

None
x_label str

X-axis label; omitted means no label.

None
y_label str

Y-axis label; omitted means no label.

None
source_text str

The source text to add to the plot.

None
ax Axes

Matplotlib axes object to plot on.

None
figsize tuple[float, float]

Figure size in inches when ax is None. Defaults to (10, 6).

None
show_markers bool

Draw a dot on the line at each callout's point. Defaults to True.

True
**kwargs Any

Additional keyword arguments for matplotlib's Axes.plot, applied to the data line. linewidth defaults to 2 and color to the primary color. Leave drawstyle at its default: callouts are placed for straight segments, so a stepped line misses them.

{}

Returns:

Name Type Description
Axes Axes

The matplotlib axes object.

Raises:

Type Description
TypeError

If df or callouts is not a pandas DataFrame.

TypeError

If value_col or x_col is not one column name, or the value column is not numeric.

TypeError

If the line's x values are neither datetime nor numeric, or the callouts' x values are not of the same type.

ValueError

If a named column is missing, or x_col and callout_x_col are both None.

ValueError

If callout_title_col and callout_text_col are both None.

ValueError

If df has fewer than 2 rows or callouts is empty.

ValueError

If the values, x values, callout x values, titles or texts contain missing values.

ValueError

If the values or the line's x values contain infinite values.

ValueError

If a callout's title and text are both blank.

ValueError

If the line's x values are not unique.

ValueError

If a callout's x value is outside the range of the line's x values.

ValueError

If the callouts cannot all be placed without overlapping; the message names the callouts left over.

Examples:

>>> from openretailscience.plots import callout_line
>>> weekly = pd.DataFrame({"week": range(1, 9), "revenue": [52, 55, 54, 81, 60, 58, 44, 57]})
>>> events = pd.DataFrame({"week": [4, 7], "event": ["Week 4", "Week 7"], "note": ["Easter", "Tills down"]})
>>> ax = callout_line.plot(
...     df=weekly, value_col="revenue", x_col="week",
...     callouts=events, callout_title_col="event", callout_text_col="note",
...     eyebrow="Trading", title="Weekly revenue and what moved it", subtitle="Revenue, £K",
... )
Source code in openretailscience/plots/callout_line.py
def plot(  # noqa: PLR0913, PLR0917
    df: pd.DataFrame,
    value_col: str,
    callouts: pd.DataFrame,
    callout_title_col: str | None = None,
    callout_text_col: str | None = None,
    x_col: str | None = None,
    callout_x_col: str | None = None,
    title: str | None = None,
    eyebrow: str | None = None,
    subtitle: str | None = None,
    x_label: str | None = None,
    y_label: str | None = None,
    source_text: str | None = None,
    ax: Axes | None = None,
    figsize: tuple[float, float] | None = None,
    show_markers: bool = True,
    **kwargs: Any,  # noqa: ANN401
) -> Axes:
    """Plot ``value_col`` as one line and call out the events in ``callouts`` on it.

    Each row of ``callouts`` becomes a bold title, wrapped text or both, joined by a leader to
    the line at that row's x value. An x value between two rows of ``df`` is anchored on the
    straight segment joining them. No callout text touches the line, another callout or a leader,
    and the y-axis is given extra headroom when the callouts need the room.

    ``df`` is not aggregated: pass one row per x value. The layout fits the figure's size and the
    axis limits at call time, so pass ``figsize`` (or an ``ax`` on a figure already at its final
    size) instead of resizing the figure afterwards, and do not change the limits afterwards. That
    rules out an ``ax`` whose y-axis is shared with a chart drawn later, and a second call on the
    same ``ax``.

    Args:
        df (pd.DataFrame): The line's data, one row per x value.
        value_col (str): The column to plot.
        callouts (pd.DataFrame): One row per callout.
        callout_title_col (str, optional): The ``callouts`` column holding each callout's bold
            title, such as the event's date already formatted for display.
        callout_text_col (str, optional): The ``callouts`` column holding each callout's text, drawn
            under the title when both are given. At least one of the two is required.
        x_col (str, optional): The column to use as the x-axis, datetime or numeric. If None, the
            index is used.
        callout_x_col (str, optional): The ``callouts`` column holding each callout's x value, of
            the same type as the line's x values. Defaults to ``x_col``; required when ``x_col`` is
            None.
        title (str, optional): The title of the plot.
        eyebrow (str, optional): Small uppercase label rendered above the title.
        subtitle (str, optional): Supporting copy rendered below the title.
        x_label (str, optional): X-axis label; omitted means no label.
        y_label (str, optional): Y-axis label; omitted means no label.
        source_text (str, optional): The source text to add to the plot.
        ax (Axes, optional): Matplotlib axes object to plot on.
        figsize (tuple[float, float], optional): Figure size in inches when ``ax`` is None.
            Defaults to (10, 6).
        show_markers (bool, optional): Draw a dot on the line at each callout's point. Defaults to True.
        **kwargs: Additional keyword arguments for matplotlib's ``Axes.plot``, applied to the data
            line. ``linewidth`` defaults to 2 and ``color`` to the primary color. Leave ``drawstyle``
            at its default: callouts are placed for straight segments, so a stepped line misses them.

    Returns:
        Axes: The matplotlib axes object.

    Raises:
        TypeError: If ``df`` or ``callouts`` is not a pandas DataFrame.
        TypeError: If ``value_col`` or ``x_col`` is not one column name, or the value column is not numeric.
        TypeError: If the line's x values are neither datetime nor numeric, or the callouts' x
            values are not of the same type.
        ValueError: If a named column is missing, or ``x_col`` and ``callout_x_col`` are both None.
        ValueError: If ``callout_title_col`` and ``callout_text_col`` are both None.
        ValueError: If ``df`` has fewer than 2 rows or ``callouts`` is empty.
        ValueError: If the values, x values, callout x values, titles or texts contain missing values.
        ValueError: If the values or the line's x values contain infinite values.
        ValueError: If a callout's title and text are both blank.
        ValueError: If the line's x values are not unique.
        ValueError: If a callout's x value is outside the range of the line's x values.
        ValueError: If the callouts cannot all be placed without overlapping; the message names
            the callouts left over.

    Examples:
        >>> from openretailscience.plots import callout_line
        >>> weekly = pd.DataFrame({"week": range(1, 9), "revenue": [52, 55, 54, 81, 60, 58, 44, 57]})
        >>> events = pd.DataFrame({"week": [4, 7], "event": ["Week 4", "Week 7"], "note": ["Easter", "Tills down"]})
        >>> ax = callout_line.plot(
        ...     df=weekly, value_col="revenue", x_col="week",
        ...     callouts=events, callout_title_col="event", callout_text_col="note",
        ...     eyebrow="Trading", title="Weekly revenue and what moved it", subtitle="Revenue, £K",
        ... )
    """
    x, y, callout_x = _validate(df, value_col, x_col, callouts, callout_x_col, callout_title_col, callout_text_col)

    created_figure = ax is None
    if ax is None:
        _, ax = plt.subplots(figsize=figsize if figsize is not None else _DEFAULT_FIGSIZE)
    y_was_autoscaled = ax.get_autoscaley_on()
    data_lim = ax.dataLim.frozen()
    line_kwargs = {
        "color": get_named_color("primary"),
        "linewidth": _LINE_WIDTH,
        "zorder": _LINE_ZORDER,
        "gid": _LINE_GID,
        **cbook.normalize_kwargs(kwargs, Line2D),
    }
    (line,) = ax.plot(x.to_numpy(), y.to_numpy(), **line_kwargs)
    styles = {
        "ax": ax,
        "title": title,
        "eyebrow": eyebrow,
        "subtitle": subtitle,
        "x_label": x_label,
        "y_label": y_label,
        "source_text": source_text,
        "show_legend": False,
        "grid_axis": "y",
        "x_margin": _X_MARGIN,
    }
    # Before the styles fit the axes box to its tick labels: the callouts are laid out in that box.
    if pd.api.types.is_datetime64_any_dtype(x):
        # The locator ticks in the data's timezone; a formatter left on UTC would label those ticks with UTC's clock.
        ax.xaxis.set_major_formatter(ConciseDateFormatter(ax.xaxis.get_major_locator(), tz=x.dt.tz))
        # The formatter writes the year beside the axis as offset text, which the tick styling does not reach.
        style = PlotStyleHelper()
        ax.xaxis.get_offset_text().set_fontproperties(get_font_properties(style.tick_font))
        ax.xaxis.get_offset_text().set_fontsize(style.tick_size)
    standard_graph_styles(**styles)

    line_xy = np.column_stack([ax.convert_xunits(x.to_numpy()), y.to_numpy()]).astype(float)
    callout_x_num = np.asarray(ax.convert_xunits(callout_x.to_numpy()), dtype=float)
    # Interpolated in the axes' scales: on a supplied log axis the drawn segments are not straight in data units.
    x_scale, y_scale = ax.xaxis.get_transform(), ax.yaxis.get_transform()
    anchors_y = y_scale.inverted().transform(
        np.interp(x_scale.transform(callout_x_num), x_scale.transform(line_xy[:, 0]), y_scale.transform(line_xy[:, 1])),
    )
    anchors_xy = np.column_stack([callout_x_num, anchors_y])

    texts, blocks = _create_texts(ax, callouts, callout_title_col, callout_text_col)
    layout, unplaced = _find_layout(ax, line_xy, anchors_xy, blocks, line.get_linewidth())
    if layout is None:
        for artist in [line, *(artist for artists in texts for artist in artists)]:
            artist.remove()
        # The removed line would otherwise stay in the data limits and scale the caller's next plot.
        # Not relim(): it leaves out collections, so would drop a scatter or fill the caller had drawn.
        ax.dataLim.set(data_lim)
        ax.set_autoscaley_on(y_was_autoscaled)
        ax.autoscale_view()
        if created_figure:
            plt.close(ax.figure)
        else:
            # With no chrome arguments this removes the title and source drawn above.
            apply_chart_chrome(ax)
        left_over = callouts.iloc[unplaced]
        name_col = callout_title_col if callout_title_col is not None else callout_text_col
        names = left_over[name_col].astype(str)
        if callout_title_col is not None and callout_text_col is not None:
            names = names.where(names.str.strip() != "", left_over[callout_text_col].astype(str))
        msg = (
            f"Could not place {len(unplaced)} of {len(callouts)} callouts without overlapping: {names.tolist()}. "
            "Use fewer or shorter callouts, or a larger figure."
        )
        raise ValueError(msg)

    ax.set_ylim(layout.ylim)
    # Applied again: headroom can widen the y tick labels, which moves the axes box and the chrome above it.
    standard_graph_styles(**styles)
    _draw_callouts(ax, layout, anchors_xy, texts, show_markers)
    return ax