Skip to content

beautiplot.plot.cbar_above#

beautiplot.plot.cbar_above #

cbar_above(
    fig: Figure,
    axes: Axes | Sequence[Axes] | ndarray,
    aximg: AxesImage,
    dy: float | None = None,
    **kwargs: Any,
) -> tuple[Colorbar, Axes]

Add a colorbar above the axes.

Parameters:

  • fig (Figure) –

    The figure to add the colorbar to.

  • axes (Axes | Sequence[Axes] | ndarray) –

    The axes to add the colorbar above.

  • aximg (AxesImage) –

    The image to create the colorbar for.

  • dy (float | None, default: None ) –

    The vertical spacing between the axes and the colorbar. If not given, the default spacing is used.

  • **kwargs (Any, default: {} ) –

    Additional keyword arguments to pass to fig.colorbar.

Returns:

  • tuple[Colorbar, Axes] –

    A tuple containing the created colorbar and the colorbar axes.

Example

See the discretized colorbar tutorial.

Source code in src/beautiplot/plot.py
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
def cbar_above(
    fig: mfigure.Figure,
    axes: matplotlib.axes.Axes | Sequence[matplotlib.axes.Axes] | np.ndarray,
    aximg: matplotlib.image.AxesImage,
    dy: float | None = None,
    **kwargs: Any,
) -> tuple[matplotlib.colorbar.Colorbar, matplotlib.axes.Axes]:
    """Add a colorbar above the axes.

    Args:
        fig: The figure to add the colorbar to.
        axes: The axes to add the colorbar above.
        aximg: The image to create the colorbar for.
        dy: The vertical spacing between the axes and the colorbar. If
            not given, the default spacing is used.
        **kwargs: Additional keyword arguments to pass to
            `fig.colorbar`.

    Returns:
        A tuple containing the created colorbar and the colorbar axes.

    Example:
        See the
        [discretized colorbar tutorial](../../../tutorials/discretized_colorbar.md).
    """  # noqa: W505
    if isinstance(axes, np.ndarray):
        axes = axes.ravel()
    ax_list = axes if isinstance(axes, list | tuple | np.ndarray) else [axes]
    pos = [ax_list[idx].get_position() for idx in (0, -1)]
    dy = fig_hspace(ax_list[0]) if dy is None else dy
    cax = fig.add_axes((
        pos[0].xmin,
        pos[0].ymax + dy,
        pos[1].xmax - pos[0].xmin,
        config.colorbar_width / fig.get_figheight(),
    ))
    cbar = fig.colorbar(aximg, cax=cax, orientation='horizontal', **kwargs)
    cax.xaxis.set_ticks_position('top')
    cax.xaxis.set_label_position('top')
    return cbar, cax