Exemplo n.º 1
0
def colorbar(
        ax: plt.Axes = None,
        mappable: mpl.cm.ScalarMappable = None,
        loc='right',
        width='5%',
        height='100%',
        borderpad=-1,
        kw_inset=(),
        kw_cbar=(),
) -> mpl.colorbar.Colorbar:
    """
    Add a colorbar aligned to the mappable (e.g., image)

    :param ax:
    :param mappable: defaults to image in the axes
    :param loc: as for legend
    :param width: relative to the axes
    :param height: relative to the axes
    :param borderpad: relative to the fontsize of the axes.
    :param kw_inset:
    :param kw_cbar:
    :return:
    """
    if ax is None:
        ax = plt.gca()
    if mappable is None:
        mappable = ax.findobj(mpl.image.AxesImage)[0]
    fig = ax.figure

    from mpl_toolkits.axes_grid1.inset_locator import inset_axes
    axins = inset_axes(ax,
                       width=width,
                       height=height,
                       loc=loc,
                       bbox_to_anchor=(0., 0., 1., 1.),
                       bbox_transform=ax.transAxes,
                       borderpad=borderpad,
                       **dict(kw_inset))
    cb = fig.colorbar(mappable, cax=axins, **dict(kw_cbar))
    return cb