Sumit
Sumit

Reputation: 221

How to adjust size of two subplots, one with colorbar and another without, in pyplot ?

Consider this example

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

plt.subplot(121)
img = plt.imshow([np.arange(0,1,.1)],aspect="auto")
ax = plt.gca()
divider = make_axes_locatable(ax)
cax = divider.append_axes("bottom", size="3%", pad=0.5)
plt.colorbar(img, cax=cax, orientation='horizontal')
plt.subplot(122)
plt.plot(range(2))
plt.show()

enter image description here I want to make these two figures (plot region without colorbar) of the same size.

The size is automatically adjusted if the colorbar is plotted vertically or if two rows are used (211, 212) instead of two columns.

Upvotes: 4

Views: 4569

Answers (2)

Jody Klymak
Jody Klymak

Reputation: 5932

You can now do this without recourse to an extra toolkit by using constrained_layout:

import numpy as np
import matplotlib.pyplot as plt

fig, axs = plt.subplots(1, 2, constrained_layout=True)
ax = axs[0]
img = ax.imshow([np.arange(0,1,.1)],aspect="auto")
fig.colorbar(img, ax=ax, orientation='horizontal')
axs[1].plot(range(2))
plt.show()

enter image description here

Upvotes: 5

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339765

One can basically do the same for the second subplot as for the first, i.e. create a divider and append an axes with identical parameters, just that in this case, we don't want a colorbar in the axes, but instead simply turn the axis off.

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

ax = plt.subplot(121)
img = ax.imshow([np.arange(0,1,.1)],aspect="auto")
divider = make_axes_locatable(ax)
cax = divider.append_axes("bottom", size="3%", pad=0.5)
plt.colorbar(img, cax=cax, orientation='horizontal')

ax2 = plt.subplot(122)
ax2.plot(range(2))
divider2 = make_axes_locatable(ax2)
cax2 = divider2.append_axes("bottom", size="3%", pad=0.5)
cax2.axis('off')
plt.show()

enter image description here

Upvotes: 8

Related Questions