python - Matplotlib。将子图与 Bbox 对齐

标签 python matplotlib

我有一个包含 6 个子图的网格。最后一个子图是正方形的。我需要将其向左移动,以便其左侧 y 轴与其上方绘图的 y 轴完全对齐。我知道我可以获取并设置 Bbox 参数,但我无法将其移向正确的方向。无论我增加还是减少 x1 和 x2,它似乎总是向右移动。

import matplotlib.pyplot as plt

fig, axs = plt.subplots(2, 3)
fig.tight_layout(pad=3.0)
fig.set_figwidth(30)
fig.set_figheight(15)

axs[1, 2].set_aspect('equal')

print(axs[1, 2].get_position())

打印命令返回:

Bbox(x0=0.7620938740079364, y0=0.16765873015873023, x1=0.8925502232142856, y1=0.4285714285714286)

enter image description here

最佳答案

.get_position() 方法确实返回给定轴的边界框。这个想法是使用方轴正上方的轴的 Bbox 来将它们与其对齐。这可以通过以下方式完成:

import matplotlib.pyplot as plt

# the figure size can be set directly from here
# I used smaller figure size than in your example for visibility
fig, axs = plt.subplots(2, 3, figsize=(15, 7))
fig.tight_layout(pad=3.0)

axs[1, 2].set_aspect('equal')

# extract positions of square and above axes
p02 = axs[0, 2].get_position()
p12 = axs[1, 2].get_position()

# make square axes with left position taken from above axes, and set position
p12 = [p02.x0, p12.y0, p12.width, p12.height]
axs[1, 2].set_position(p12)

plt.show()

结果是:

left-align axes matplotlib subplot

关于python - Matplotlib。将子图与 Bbox 对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64066011/

相关文章:

python - 如何删除 pyplot.bar 中的轴?

python - Beautiful Soup 在每个字符之间添加空格

python - 将 RGB 图像数组乘以标量后使用 plt.imshow 获取黑色图

python - 如何在 Django 管理中删除面包屑

python - 如何在 python 3 中将字符串添加到 json 值

python - 以对数刻度间距绘制 x 轴但不以指数形式标记它

linux - Linux 与 mswindows 中的 Matplotlib 绘图

javascript - 来自 matplotlib 的交互式_独立_输出

python - 如何设置和拆卸用于单元测试的临时 Django 数据库?

python - 过滤器在Elasticsearch中不起作用