manualcolorbar#

manualcolorbar(data=None, vmin=0, vmax=1, vcenter=None, colors=None, values=None, cmap=None, norm=None, label=None, labelkwargs=None, ticks=None, ticklabels=None, fig=None, ax=None, cax=None, axkwargs=None, **kwargs)[source]#

Add a colorbar to a plot that does not support one by default.

There are three main use cases, from least to most manual:

  • The most common use case is to supply the data used for plotting directly via data; the function will the infer the lower and upper limits and construct the colorbar.

  • Alternatively, the lower and upper limits can be provided manually via vmin and vmax.

  • Finally, the colors themselves can be provided via colors, optionally mapped to values, and potentially also supplied with custom ticklabels.

Parameters:
  • data (arr) – if provided, compute the colorbar from these data

  • vmin (float) – the minimum of the colormap (optional if data are provided)

  • vmax (float) – the maximum of the colormap (optional if data are provided)

  • vcenter (float) – the center of the colormap (optional)

  • colors (arr) – if provided, use these colors directly instead

  • values (arr) – if provided, the values corresponding to the specific colors

  • cmap (str/arr) – the colormap to use

  • norm (Norm) – the Matplotlib norm to use (if not provided, use the midpoint norm with vmin, vmax, etc.)

  • label (str) – the label for the colorbar

  • labelkwargs (dict) – passed to the colorbar label

  • ticks (list) – the tick locations to use for the colorbar

  • ticklabels (list) – the tick labels to use

  • ax (Axes) – the “parent” axes to associate the colorbar with

  • cax (Axes) – the axes to draw the colorbar into

  • axkwargs (dict) – if creating a new colorbar axes, the arguments for creating it

  • kwargs (dict) – passed to matplotlib.colorbar.ColorbarBase()

Examples:

# Create a default colorbar
sc.manualcolorbar()

# Add a colorbar to non-mappable data (e.g. a scatterplot)
n = 1000
x = np.random.randn(n)
y = np.random.randn(n)
c = x**2 + y**2
plt.scatter(x, y, c=c)
sc.manualcolorbar(c)

# Create a custom colorbar with a custom label
sc.manualcolorbar(
    vmin=-20,
    vmax=40,
    vcenter=0,
    cmap='orangeblue',
    label='Cold/hot',
    orientation='horizontal',
    labelkwargs=dict(rotation=10, fontweight='bold'),
    axkwargs=[0.1,0.5,0.8,0.1],
)

# Create a completely custom colorbar
n = 12
x = np.arange(n)
values = np.sqrt(np.arange(n))
colors = sc.gridcolors(n)
plt.scatter(x, values, c=colors)
plt.grid(True)

ticklabels = ['' for i in range(n)]
for i in [0, 2, 4, 10, 11]:
    ticklabels[i] = f'Color {i} is nice'
cb = sc.manualcolorbar(
    colors=colors,
    values=values,
    ticks=values,
    ticklabels=ticklabels,
    spacing='proportional'
)
New in version 3.1.0.