【问题标题】:alignment of stacked subplots堆叠子图的对齐
【发布时间】:2023-03-13 07:14:01
【问题描述】:

编辑:

我找到了一个答案(见下文)如何在子图中对齐图像:

for ax in axes:
    ax.set_anchor('W')

编辑结束

我有一些用 imshow 绘制的数据。它在 x 方向上很长,所以我通过在垂直堆叠的子图中绘制数据切片将其分成多行。我对结果感到满意,但对于我希望与其他子图左对齐的最后一个子图(不如其他子图那么宽)。

下面的代码是用 Python 2.7.1 和 matplotlib 1.2.x 测试的。

#! /usr/bin/env python

import matplotlib.pyplot as plt
import numpy as np

x_slice = [0,3]
y_slices = [[0,10],[10,20],[20,30],[30,35]]
d = np.arange(35*3).reshape((35,3)).T
vmin = d.min()
vmax = d.max()
fig, axes = plt.subplots(len(y_slices), 1)


for i, s in enumerate(y_slices):
    axes[i].imshow( 
        d[ x_slice[0]:x_slice[1], s[0]:s[1] ], 
        vmin=vmin, vmax=vmax,
        aspect='equal',
        interpolation='none'
    )

plt.show()

结果

根据Zhenya 的提示,我使用了axis.get/set_position。我尝试将宽度减半,但我不明白它的效果

for ax in axes:
    print ax.get_position()

p3 = axes[3].get_position().get_points()
x0, y0 = p3[0]
x1, y1 = p3[1]
# [left, bottom, width, height]
axes[3].set_position([x0, y0, (x1-x0)/2, y1-y0])

get_position 给了我每个子图的 bbox:

for ax in axes:
    print ax.get_position()

Bbox(array([[ 0.125     ,  0.72608696],
            [ 0.9       ,  0.9       ]]))
Bbox(array([[ 0.125     ,  0.5173913 ],
            [ 0.9       ,  0.69130435]]))
Bbox(array([[ 0.125     ,  0.30869565],
            [ 0.9       ,  0.4826087 ]]))
Bbox(array([[ 0.125     ,  0.1       ],
            [ 0.9       ,  0.27391304]]))

所以所有子图都具有完全相同的水平范围(0.125 到 0.9)。从较窄的第 4 个子图来看,子图中的图像以某种方式居中。

让我们看看 AxesImage 对象:

for ax in axes:
    print ax.images[0]

AxesImage(80,348.522;496x83.4783)
AxesImage(80,248.348;496x83.4783)
AxesImage(80,148.174;496x83.4783)
AxesImage(80,48;496x83.4783)

同样,第四张图片的水平范围也相同。

接下来试试 AxesImage.get_extent():

for ax in axes:
    print ax.images[0].get_extent()

# [left, right, bottom, top]
(-0.5, 9.5, 2.5, -0.5)
(-0.5, 9.5, 2.5, -0.5)
(-0.5, 9.5, 2.5, -0.5)
(-0.5, 4.5, 2.5, -0.5)

存在差异(右),但左值对所有人都相同,那么为什么第 4 个居中?

编辑:它们都是居中的......

【问题讨论】:

    标签: python numpy matplotlib


    【解决方案1】:

    Axis.set_anchor 工作至今(我只是希望我现在不必手动调整太多):

    for ax in axes:
        ax.set_anchor('W')
    

    【讨论】:

      【解决方案2】:

      您可以手动控制子图的位置,如下所示:

      for ax in axes:
        print ax.get_position()
      

      ax[3].set_position([0.1,0.2,0.3,0.4])
      

      或者,您可能想看看GridSpec

      【讨论】:

      • 感谢Zhenya,我尝试了axis.set_position,但似乎发生了一些我不明白的事情 - 请参阅更新后的问题。
      【解决方案3】:

      我经常发现ax.set_position 很难准确。 我更喜欢使用plt.subplots_adjust(wspace=0.005) # adjust the width between the subplots 来调整两个水平子图之间的距离。

      您也可以调整垂直距离。

      【讨论】:

        猜你喜欢
        • 2015-10-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-10-17
        相关资源
        最近更新 更多