Sometimes, we want to have one color bar for all subplots with Python.
in this article, we’ll look at how to have one color bar for all subplots with Python.
How to have one color bar for all subplots with Python?
To have one color bar for all subplots with Python, we can use matplotlib’s subplots_adjust and colorbar methods.
For instance, we write
import numpy as np
import matplotlib.pyplot as plt
fig, axes = plt.subplots(nrows=2, ncols=2)
for ax in axes.flat:
im = ax.imshow(np.random.random((10,10)), vmin=0, vmax=1)
fig.subplots_adjust(right=0.8)
cbar_ax = fig.add_axes([0.85, 0.15, 0.05, 0.7])
fig.colorbar(im, cax=cbar_ax)
plt.show()
to call subplots_adjust on the fig subplot with the right argument to adjust the position of the subplots.
Then we add the color bar into its own axis with
fig.colorbar(im, cax=cbar_ax)
Conclusion
To have one color bar for all subplots with Python, we can use matplotlib’s subplots_adjust and colorbar methods.