使用axis_grid工具包自定义坐标轴布局

3 投票
1 回答
711 浏览
提问于 2025-04-18 10:10

我在使用 make_axes_locatable/append_axes 这个工具包的时候遇到了问题,特别是当我把这些函数嵌套使用时,比如:

divider1 = make_axes_locatable(ax1)
divider2 = make_axes_locatable(divider1.append_axes(...))

如果我用上面的代码创建三个坐标轴,就像在 (4,5,6) 里那样,主要的坐标轴(ax4)就会被右边的另外两个坐标轴遮住(见下面的图和 这个链接)。我猜 make_axes_locatable/append_axes 不是这样使用的。

这里插入图片描述

我想要的只是把颜色条放在 ax1 的顶部(就像下面的图中那样 - 这个链接),而是放在表格下面的空白区域。使用 make_axes_locatable 的好处是,如果我调整图形大小,图形看起来依然不错,这和手动创建坐标轴对象(用 fig.add_axes(),代码在 4 的最后)相比要好很多。

有没有人能告诉我怎么把右边的坐标轴(ax2)分开,这样表格下面的空间都能用来放颜色条和它的刻度标签?

blabla

1 个回答

2

我不太确定你能否仅通过 AxesDivider.append_axes 来实现这个功能,因为根据 文档,这个方法是“在给定位置创建一个与主坐标轴高度(或宽度)相同的坐标轴。”你想要的是右边的坐标轴高度和左边的不一样。

另一种选择是创建两个子图,然后用一个分隔符把右边的子图分开:

import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable

ax = plt.subplot(121)
ax2 = plt.subplot(122)
divider = make_axes_locatable(ax2)
ax3  = divider.append_axes("bottom", size="50%", pad=0.5)

plt.show()

或者直接创建一个 Divider(不使用 makes_axes_locatable),就像在 这里和下面所示的那样:

import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid import Divider
import mpl_toolkits.axes_grid.axes_size as Size

fig1 = plt.figure(1, (5.5, 4.))

# the rect parameter will be ignore as we will set axes_locator
rect = (0.1, 0.1, 0.8, 0.8)
ax = [fig1.add_axes(rect, label="%d"%i) for i in range(3)]

horiz = [Size.Scaled(1.5), Size.Fixed(.5), Size.Scaled(1.),
         Size.Scaled(.5)]

vert = [Size.Scaled(1.), Size.Fixed(.5), Size.Scaled(1.5)]

# divide the axes rectangle into grid whose size is specified by horiz * vert
divider = Divider(fig1, rect, horiz, vert, aspect=False)
ax[0].set_axes_locator(divider.new_locator(nx=0, ny=0, ny1=3))
ax[1].set_axes_locator(divider.new_locator(nx=2, ny=2))
ax[2].set_axes_locator(divider.new_locator(nx=2, ny=0))

plt.show()

如果完全不需要使用 Divider,你也可以使用 GridSpec

import matplotlib.pyplot as plt

ax1 = plt.subplot2grid((2,2), (0,0), rowspan=2)
ax2 = plt.subplot2grid((2,2), (0, 1))
ax3 = plt.subplot2grid((2,2), (1, 1))

plt.show()

这三种方法都会创建出大致如下的效果:

three axes in a figure

这三种方法在我调整大小时看起来都还不错,至少在这个简单的例子中是这样的。

编辑 你可以使用 gridspecSubplot 来在左边得到一个宽高比为1的坐标轴,右边则是一对与左边坐标轴的顶部和底部对齐的坐标轴。关键是要通过 width_ratiosheight_ratios 来设置 gridspec 的宽高比。当这个图形被调整大小时,右边坐标轴的顶部和底部仍然会与左边坐标轴的顶部和底部对齐。

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

fig = plt.figure()

# grid spec for left and right columns
gs0 = gridspec.GridSpec(1, 2,width_ratios=[1,1], height_ratios=[1,1])

# gird spec for left axes with aspect ratio of 1
gs00 = gridspec.GridSpecFromSubplotSpec(1, 1, subplot_spec=gs0[0], width_ratios=[1], height_ratios=[1])
ax1 = plt.Subplot(fig, gs00[0])
fig.add_subplot(ax1)

# grid spec for two right axes
gs01 = gridspec.GridSpecFromSubplotSpec(2, 1, subplot_spec=gs0[1])
ax2 = plt.Subplot(fig, gs01[0])
ax3 = plt.Subplot(fig, gs01[1])
fig.add_subplot(ax2)
fig.add_subplot(ax3)

plt.show()

enter image description here

撰写回答