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

Sum*_*mit 2 python matplotlib

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()
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明 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.

Imp*_*est 6

对于第二个子图,基本上可以对第一个子图执行相同的操作,即创建一个分隔符并附加一个具有相同参数的轴,只是在这种情况下,我们不需要轴中的颜色条,而是简单地转动轴离开。

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()
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明


Jod*_*mak 5

现在,您可以使用 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()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述