lbellomo lbellomo - 12 days ago 5
Python Question

Losing edge values in last colormap subplot matplotlib

I'm using python 3.5.2 and matplotlib 1.5.3.

I'm doing some colormaps with the "y" axis shared.
The problem is that when placing the colorbar in the last subplot I lose the first and last tick on the x axis. But if you enlarge the figure (figsize = (12,3) for example) some white space appears at the edges of the other subplot.

import numpy as np
import matplotlib.pyplot as plt

matrix = np.random.random((10, 10, 3))
fig = plt.figure(figsize=(10, 3)) # Try a figsize=(12, 3)

for i in range(3):
if i == 0:
ay1 = plt.subplot(1, 3, i+1)
else:
plt.subplot(1, 3, i+1, sharey=ay1)
plt.imshow(matrix[:, :, i], interpolation='nearest')
if i == 2:
plt.colorbar()
plt.show()


What is the correct way to do it?

Answer

Using sharey only makes sense, if you use different sized images. But when the images are differently sized, in some parts of the figure there is nothing - which will be painted white.

On the other hand, if you do have same size pictures as here, there is no need to use sharey. In that case, you can simply plot your data and add a colorbar.

import numpy as np
import matplotlib.pyplot as plt

matrix = np.random.random((10, 10, 3))

fig, ax = plt.subplots(1,3, figsize=(12, 3))
plt.subplots_adjust(left=0.05, right=0.85)
for i in range(3):
    im = ax[i].imshow(matrix[:, :, i], interpolation='nearest')
    ax[i].set_aspect("equal")

plt.draw()
p = ax[-1].get_position().get_points().flatten()
ax_cbar = fig.add_axes([0.9,p[1], 0.02, p[3]-p[1]] )
plt.colorbar(im, cax=ax_cbar)

plt.show()

enter image description here