我创建了一个函数,它创建具有绝对大小的轴,并以大多数方式起作用,例如plt.subplots(...),例如通过允许共享 y 轴或 x 轴并将轴作为成形的 numpy 数组返回。假设您将figsize 设置得足够大,它将轴在其网格区域内居中,从而在它们自身和图形边缘之间提供尽可能多的空间。
参数包括图形的绝对高度和宽度(有关详细信息,请参阅matplotlib documentation)以及轴的绝对高度和宽度,如原始问题中所要求的那样。
from typing import Tuple
from matplotlib import pyplot as plt
import numpy as np
def subplots_with_absolute_sized_axes(
nrows: int, ncols: int,
figsize: Tuple[float, float],
axis_width: float, axis_height: float,
sharex: bool=False, sharey: bool=False) -> Tuple[plt.Figure, numpy.ndarray]:
''' Create axes with exact sizes.
Spaces axes as far from each other and the figure edges as possible
within the grid defined by nrows, ncols, and figsize.
Allows you to share y and x axes, if desired.
'''
fig = plt.figure(figsize=figsize)
figwidth, figheight = figsize
# spacing on each left and right side of the figure
h_margin = (figwidth - (ncols * axis_width)) / figwidth / ncols / 2
# spacing on each top and bottom of the figure
v_margin = (figheight - (nrows * axis_height)) / figheight / nrows / 2
row_addend = 1 / nrows
col_addend = 1 / ncols
inner_ax_width = axis_width / figwidth
inner_ax_height = axis_height / figheight
axes = []
sharex_ax = None
sharey_ax = None
for row in range(nrows):
bottom = (row * row_addend) + v_margin
for col in range(ncols):
left = (col * col_addend) + h_margin
if not axes:
axes.append(fig.add_axes(
[left, bottom, inner_ax_width, inner_ax_height]))
if sharex:
sharex_ax = axes[0]
if sharey:
sharey_ax = axes[0]
else:
axes.append(fig.add_axes(
[left, bottom, inner_ax_width, inner_ax_height],
sharex=sharex_ax, sharey=sharey_ax))
return fig, np.flip(np.asarray(list(axes)).reshape((nrows, ncols)), axis=0)