Skip to content

sec_axis

sec_axis(
    transform: Callable[[float], float] | None = None,
    *,
    name: SecondaryName = None,
    breaks: SecondaryBreaks = None,
    labels: SecondaryLabels = None,
    guide: Union = None,
) -> SecondaryAxisSpec

Add a secondary axis on the other side of a continuous position scale (ggplot2).

The secondary axis shows the primary axis through transform: its breaks are chosen over the transformed axis range and placed where the primary axis has the matching value. Works with position=, facets, coord_flip() and log or reverse primary scales.

Parameters:

  • transform (callable, default: None ) –

    Function of one primary value returning the secondary value, e.g. lambda celsius: celsius * 1.8 + 32. It is called once per value on 1000 points over the axis range and must be strictly monotonic over the data. None is the identity.

  • name (str or derive(), default: None ) –

    Secondary axis title; derive() takes the primary title. No title by default.

  • breaks (list of float or derive(), default: None ) –

    Break values in secondary units; derive() takes the primary scale's breaks. Chosen over the secondary range by default (log breaks on a log scale).

  • labels (list of str, str or derive(), default: None ) –

    One label per break (needs breaks), or a format such as "{.0f} °F"; derive() takes the primary scale's labels and format.

  • guide ((axis, none), default: 'axis' ) –

    'none' hides the secondary axis.

Returns:

  • SecondaryAxisSpec –

    Pass it as sec_axis= to scale_x_continuous() / scale_y_continuous().

Raises:

  • UnsupportedValueError –

    If transform is not callable, or another option has the wrong type.

  • SpecError –

    If labels do not match the breaks or the guide is unknown. A transform that is not monotonic over the axis range fails when the plot is rendered.

Examples:

>>> from ggrust import *
>>> data = {"month": [1, 2, 3, 4, 5, 6], "celsius": [3.1, 4.2, 8.0, 12.5, 16.9, 20.3]}
>>> plot = (
...     ggplot(data, aes("month", "celsius"))
...     + geom_line()
...     + scale_y_continuous(
...         "Temperature (°C)", sec_axis=sec_axis(lambda c: c * 1.8 + 32, name="°F")
...     )
... )