I am facing a strange behaviour with my code.
I don’t understand why the subplot at the top left has a different space between the imshow and the colorbar compared to the subplot at the top right.
And also I don’t understand why the colorbar at the bottom is not aligned with the one at the top right.
Can you explain this ?
import matplotlib.pyplot as plt
import numpy as np
matrix = np.random.rand(100, 100)
mosaic = "AB;CC"
fig = plt.figure(layout="constrained")
ax_dict = fig.subplot_mosaic(mosaic)
img = ax_dict['A'].imshow(matrix, aspect="auto")
fig.colorbar(img, ax=ax_dict['A'])
img = ax_dict['B'].imshow(matrix, aspect="auto")
fig.colorbar(img, ax=ax_dict['B'])
img = ax_dict['C'].imshow(matrix, aspect="auto")
fig.colorbar(img, ax=ax_dict['C'])
plt.show()
I don’t know the actual answer, but you can make a workaround by messing with the padding. This produces something sort of reasonable. I hate messing with values like this though. You can check out other manual placement options in this example.
import matplotlib.pyplot as plt
import numpy as np
matrix = np.random.rand(100, 100)
mosaic = "AB;CC"
fig = plt.figure(layout="constrained")
ax_dict = fig.subplot_mosaic(mosaic)
img = ax_dict['A'].imshow(matrix, aspect="auto")
fig.colorbar(img, ax=ax_dict['A'], pad=-0.08)
img = ax_dict['B'].imshow(matrix, aspect="auto")
fig.colorbar(img, ax=ax_dict['B'], pad=0.04)
img = ax_dict['C'].imshow(matrix, aspect="auto")
fig.colorbar(img, ax=ax_dict['C'], pad=0.02)
plt.show()
2