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
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
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