Skip to main content
 首页 » 编程设计

python之使用 axis_grid 工具包自定义轴布局

2025年05月04日9lhb25

我在 axis_grid 工具包中遇到 make_axes_locatable/append_axes 问题,当函数调用是嵌套时,例如,

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

如果我使用上面的代码创建 3 个轴,如 (4,5,6) ,则主轴 (ax4) 隐藏在右侧其他两个轴的后面(参见下图和 this gist )。我想 make_axes_locatable/append_axes 不应该以这种方式使用。

我想要的只是将颜色条不放在 ax1 的顶部(如下图 - this gist ),而是放在表格下方的空白区域。 make_axes_locatable 的优点是,如果我调整它的大小,图形仍然看起来不错,这与使用 fig.add_axes() 手动创建轴对象形成对比(代码在 4 的末尾).

谁能告诉我如何拆分右轴 (ax2) s.t.表格下方的所有空间都用于颜色栏及其刻度标签?

请您参考如下方法:

我不确定您是否可以仅使用 AxesDivider.append_axes 来执行此操作,因为根据 documentation该方法“在给定位置创建一个与主轴具有相同高度(或宽度)的轴。”您希望右侧的轴与左侧的轴具有不同的高度。

另一种选择是创建两个子图并使用分隔线将右边的子图分开:

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),如图here及以下:

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

所有这三个选项都会创建类似这样的东西:

当我调整它们的大小时,所有这三个看起来都不错,至少在这个简单的例子中是这样。

编辑 您可以使用 gridspec 和 Subplot 获取左侧纵横比为 1 的轴和右侧一对与顶部和底部对齐的轴左轴。诀窍是使用 width_ratios 和 height_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()