# 使用 AxesGrid 时出现意外结果

[英]Unexpected result while using AxesGrid

This code这段代码

``````import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import AxesGrid

mat0 = [[1, 2], [3, 4], [5, 6], [7, 8]] # 4 rows × 2 columns
mat1 = [[-2, 0, 2, 4], [0, 2, 4, 6]]    # 2 rows × 4 columns

fig = plt.figure(figsize=(9, 3))
grid = AxesGrid(fig, 111, nrows_ncols=(1,2),
cbar_size="6%", cbar_location="right", cbar_mode="single")
for ax, mat in zip(grid.axes_all, (mat0, mat1)): im = ax.imshow(mat)
grid.cbar_axes[0].colorbar(im)

plt.figure()
plt.imshow(mat0)
plt.colorbar()

plt.show()
``````

produces two Figures产生两个数字

I expected to see, in the first one, a tall rectangle in the left, as in the second Figure.我希望在第一个图中看到左侧有一个高矩形，如第二个图所示。

Of course I'm not understanding what is really happening with AxesGrid.当然，我不了解 AxesGrid 到底发生了什么。

How can I have the two Images side by side, without the tall one being truncated?我怎样才能并排放置两个图像，而不截断高大的图像？

Is an image worth 1000 words?一张图片值1000字吗？

If you're dealing with images of different dimensions, it can be tricky to display them side by side with equal height while maintaining their aspect ratio.如果您要处理不同尺寸的图像，在保持宽高比的同时以相同的高度并排显示它们可能会很棘手。 A simpler alternative, and for me a more elegant solution, might be to just use subplots and share the colorbar.一个更简单的替代方案，对我来说是一个更优雅的解决方案，可能是只使用子图并共享颜色条。 Here's how you can do it:以下是您的操作方法：

``````import matplotlib.pyplot as plt
import numpy as np

mat0 = np.array([[1, 2], [3, 4], [5, 6], [7, 8]]) # 4 rows × 2 columns
mat1 = np.array([[-2, 0, 2, 4], [0, 2, 4, 6]])    # 2 rows × 4 columns

fig, axs = plt.subplots(1, 2, figsize=(9, 3))

cax = axs[0].imshow(mat0)
axs[1].imshow(mat1)

fig.colorbar(cax, ax=axs.ravel().tolist(), shrink=0.5)

plt.show()
``````

In this script, `subplots` creates a 1x2 grid of axes.在此脚本中， `subplots`创建一个 1x2 轴网格。 The images are displayed on these axes using `imshow` .使用`imshow`将图像显示在这些轴上。 The colorbar is shared across the subplots with the help of `fig.colorbar` .`fig.colorbar`的帮助下，颜色条在子图中共享。 The `shrink` parameter adjusts the size of the colorbar. `shrink`参数调整颜色条的大小。 You may need to adjust the `figsize` parameter to better suit your data and display size.您可能需要调整`figsize`参数以更好地适应您的数据和显示大小。

This is the result:这是结果：

I hope this helps.我希望这有帮助。