繁体   English   中英

如何在 pyplot 中调整两个子图的大小,一个带颜色条,另一个不带颜色条?

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

考虑这个例子

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()

在此处输入图像描述 我想让这两个图形(没有颜色条的绘图区域)大小相同。

如果垂直绘制颜色条或使用两行(211、212)而不是两列,则会自动调整大小。

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

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()

在此处输入图像描述

您现在可以通过使用 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()

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM