You can specify the axis object with any of the matplotlib built-in methods, and then use it for your color bar, for example:
import matplotlib.pyplot as plt import numpy as np ax2 = plt.subplot2grid((1,6), (0, 5), colspan=1) ax1 = plt.subplot2grid((1,6), (0, 0), colspan=5) plt.imshow(np.random.random((10,10))) plt.colorbar(cax=ax2) plt.show()
This will result in something like:

Although this will not help if your imshow axes become very flat (due to aspect = "equal", this may happen).
If you want to handle such cases, you can
Adjust the size of the shape to an aspect of your mesh, for example.
fig = figure (figsize = grid.shape [1] * 1.5 / dpi, grid.shape [0] / dpi)
Read the coordinates of ax1 AFTER plotting, create ax2 immediately after that with the coordinates converted correctly, and then use ax2 for the color bar. This does not behave well when you resize the window, but can work if you simply create graphics as image files automatically.
If 2. what you need, I can add an example for this, but I will only do this work if you are sure that this is what you need.
Hi Torsten
source share