How can I create a standard colorbar for a series of plots in python How can I create a standard colorbar for a series of plots in python python python

How can I create a standard colorbar for a series of plots in python


Not to steal @ianilis's answer, but I wanted to add an example...

There are multiple ways, but the simplest is just to specify the vmin and vmax kwargs to imshow. Alternately, you can make a matplotlib.cm.Colormap instance and specify it, but that's more complicated than necessary for simple cases.

Here's a quick example with a single colorbar for all images:

import numpy as npimport matplotlib.pyplot as plt# Generate some data that where each slice has a different range# (The overall range is from 0 to 2)data = np.random.random((4,10,10))data *= np.array([0.5, 1.0, 1.5, 2.0])[:,None,None]# Plot each slice as an independent subplotfig, axes = plt.subplots(nrows=2, ncols=2)for dat, ax in zip(data, axes.flat):    # The vmin and vmax arguments specify the color limits    im = ax.imshow(dat, vmin=0, vmax=2)# Make an axis for the colorbar on the right sidecax = fig.add_axes([0.9, 0.1, 0.03, 0.8])fig.colorbar(im, cax=cax)plt.show()

enter image description here


Easiest solution is to call clim(lower_limit, upper_limit) with the same arguments for each plot.


This only answer half of the question, or rather starts a new one.If you change

data *= np.array([0.5, 1.0, 1.5, 2.0])[:,None,None]

to

data *= np.array([2.0, 1.0, 1.5, 0.5])[:,None,None]

your colorbar will go from 0 to 0.5 which in this case is dark blue to slightly lighter blue and will not cover the whole range (0 to 2).The colorbar will only show the colors from the last image or contour regardless of vmin and vmax.