Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 929
Sumit Avatar asked Oct 26 '25 10:10

Sumit


2 Answers

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

like image 199
ImportanceOfBeingErnest Avatar answered Oct 28 '25 23:10

ImportanceOfBeingErnest


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

like image 39
Jody Klymak Avatar answered Oct 29 '25 00:10

Jody Klymak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!