我正在尝试使用 imshow 绘制三个共享单个颜色条的二维数组。下面是一个有效的示例,但第三个图显示的比前两个小。如何使所有三个图的大小相同?
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
# Create three random 2-dimensional arrays of size 256x256
array1 = np.random.random((256, 256))
array2 = np.random.random((256, 256))
array3 = np.random.random((256, 256))
# Create a figure with three subplots
fig, axes = plt.subplots(1, 3, figsize=(15, 5))
# Plot each array using imshow in a subplot
im1 = axes[0].imshow(array1, cmap='viridis')
im2 = axes[1].imshow(array2, cmap='viridis')
im3 = axes[2].imshow(array3, cmap='viridis')
# Set titles for the subplots
axes[0].set_title('Array 1')
axes[1].set_title('Array 2')
axes[2].set_title('Array 3')
# Use make_axes_locatable to add a colorbar to the right of the last plot
divider = make_axes_locatable(axes[2])
cax = divider.append_axes("right", size="5%", pad=0.5)
cbar = plt.colorbar(im3, cax=cax)
# Adjust spacing between subplots
plt.tight_layout()
# Display the plots
plt.show()
输出:
第三个图和前两个图之间的大小差异可能是由于使用 make_axes_locatable 添加到第三个图右侧的颜色条造成的。
为了确保所有三个图具有相同的大小,您可以在创建子图时使用 gridspec_kw 参数调整子图宽度。您可以通过以下方式修改代码来实现此目的:
fig, axes = plt.subplots(1, 3, figsize=(15, 5), gridspec_kw={'width_ratios': [1, 1, 1.05]})
通过调整 gridspec_kw 中的 width_ratios 参数,您可以确保所有三个子图具有相同的宽度,同时仍然适应第三个图上的颜色条。
希望对你有帮助。