3

I'm trying to make a subplot with three plots next to each other, and then a colorbar on the right side of the last plot (see figure).

I'm doing it with this code:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rcParams
from mpl_toolkits.axes_grid1 import make_axes_locatable

x = np.linspace(1, 100, 100)
y = np.linspace(0.1, 10, 100)
z = x[:, np.newaxis] + y[np.newaxis, :]

fig, ax = plt.subplots(1, 3, figsize=(12, 4))

ax[0].contourf(x, y, z)
ax[0].set_xlabel('x')
ax[0].set_ylabel('y')

ax[1].contourf(x, y, z)
ax[1].set_xlabel('x')
ax[1].set_ylabel('y')

plt.contourf(x, y, z)
ax[2].set_xlabel('x')
ax[2].set_ylabel('y')

divider = make_axes_locatable(plt.gca())
cax = divider.append_axes("right", "10%", pad="3%")

plt.colorbar(cax=cax)
plt.tight_layout()
plt.show()

My problem is that 1) I don't think the first two plots are completely square (which I would like them to be), 2) the last plot that includes the colorbar is smaller in width than the two others. Is there some easy trick to fix this, or do I manually have to go in and give one a little more padding than the other an so on.

enter image description here

Denver Dang
  • 2,433
  • 3
  • 38
  • 68
  • 2
    The answer to your problem is very much similar to the **4th** answer on [this](https://stackoverflow.com/questions/13784201/matplotlib-2-subplots-1-colorbar/38940369#38940369) page. – Sheldore Aug 30 '18 at 23:59

1 Answers1

3

If you don't want the subplot to eat into the third axes, already create an extra axes for it when you make the subplots.

To make the plots square, you need to set the aspect ratio: axes.set_aspect(10).

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(1, 100, 100)
y = np.linspace(0.1, 10, 100)
z = x[:, np.newaxis] + y[np.newaxis, :]

gridspec = {'width_ratios': [1, 1, 1, 0.1]}
fig, ax = plt.subplots(1, 4, figsize=(12, 4), gridspec_kw=gridspec)

ax[0].contourf(x, y, z)
ax[0].set_xlabel('x')
ax[0].set_ylabel('y')

ax[1].contourf(x, y, z)
ax[1].set_xlabel('x')
ax[1].set_ylabel('y')

plt.sca(ax[2])
plt.contourf(x, y, z)
ax[2].set_xlabel('x')
ax[2].set_ylabel('y')

for axes in ax[:3]:
    axes.set_aspect(10)

cax = ax[3]
plt.colorbar(cax=cax)
plt.tight_layout()
plt.show()

plot output

Joooeey
  • 3,394
  • 1
  • 35
  • 49
  • 2
    I assume from the OP's output that he/she wants the colorbar height to be the same as the subplot – Sheldore Aug 31 '18 at 00:04