I'm trying to add a colorbar to a plot consisting of two subplots with equal aspect ratios, i.e. with set_aspect('equal')
:
The code used to create this plot can be found in this IPython notebook.
The image created using the code shown below (and here in the notebook) is the best result I could get, but it is still not quite what I want.
plt.subplot(1,2,1)
plt.pcolormesh(rand1)
plt.gca().set_aspect('equal')plt.subplot(1,2,2)
plt.pcolormesh(rand2)
plt.gca().set_aspect('equal')plt.tight_layout()from mpl_toolkits.axes_grid1 import make_axes_locatable
divider = make_axes_locatable(plt.gca())
cax = divider.append_axes("right", size="5%", pad=0.05)plt.colorbar(cax=cax)
This question seems related:
- Matplotlib 2 Subplots, 1 Colorbar
I'm still not sure what you exactly want but I guess you want to subplots using pcolormesh
to have the same size when you add a colorbar?
What I have now is a bit of a hack as I add a colorbar
for both subplots to ensure they have the same size. Afterwords I remove the first colorbar
. If the result is what you want I can look into a more pythonic way of achieving it. For now it is still a bit vague as to what you exactly want.
import numpy
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatabledata = numpy.random.random((10, 10))fig = plt.figure()ax1 = fig.add_subplot(1,2,1, aspect = "equal")
ax2 = fig.add_subplot(1,2,2, aspect = "equal")im1 = ax1.pcolormesh(data)
im2 = ax2.pcolormesh(data)divider1 = make_axes_locatable(ax1)
cax1 = divider1.append_axes("right", size="5%", pad=0.05)divider2 = make_axes_locatable(ax2)
cax2 = divider2.append_axes("right", size="5%", pad=0.05)#Create and remove the colorbar for the first subplot
cbar1 = fig.colorbar(im1, cax = cax1)
fig.delaxes(fig.axes[2])#Create second colorbar
cbar2 = fig.colorbar(im2, cax = cax2)plt.tight_layout()plt.show()