You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何利用Matplotlib轴单位自动设置2D绘图的宽高比?

Matplotlib轴单位能否自动适配等宽高比?

我希望借助Matplotlib中带预定义转换关系的轴单位来定义2D绘图的宽高比。此前我通过手动计算所需宽高比实现需求,但了解到Matplotlib的axis units功能后,认为它应该能自动完成该操作,不过实际测试发现axis units并未被用于宽高比计算,特来确认是否确实如此,或是我遗漏了某些配置。

以下是示例代码说明我的需求:

import numpy as np
import matplotlib.pyplot as plt
from basic_units import cm, inch

def gauss(sigma=0.1):
    x = y = np.linspace(-0.5, 0.4, 10)
    X, Y = np.meshgrid(y, x)
    return np.exp(-(X**2 + Y**2) / (2 * sigma**2))

z = np.tile(gauss(), (5, 5))

plt.figure()
plt.imshow(z, extent=[-2.5,2.5,-2.5,2.5])

ax = plt.gca()
ax.xaxis.set_units(cm)
ax.yaxis.set_units(inch)

ax.set_xlim(-2.5*cm, 2.5*cm)
ax.set_ylim(-2.5*inch, 2.5*inch)

ax.set_aspect('equal')

plt.show()
import numpy as np
import matplotlib.pyplot as plt
from basic_units import cm, inch

def gauss(sigma=0.1):
    x = y = np.linspace(-0.5, 0.4, 10)
    X, Y = np.meshgrid(y, x)
    return np.exp(-(X**2 + Y**2) / (2 * sigma**2))

z = np.tile(gauss(), (5, 5))

plt.figure()
plt.imshow(z, extent=[-2.5,2.5,-2.5,2.5])

ax = plt.gca()
ax.xaxis.set_units(cm)
ax.yaxis.set_units(inch)

ax.set_xlim(-2.5*cm, 2.5*cm)
ax.set_ylim(-2.5*inch, 2.5*inch)
ax.set_xlabel(cm)
ax.set_ylabel(inch)

ax.set_aspect('equal')

plt.show()

运行代码需依赖Matplotlib官方提供的basic_units模块。我预期设置set_aspect('equal')后,绘图的物理宽高比应为2.54(对应英寸与厘米的转换系数),但实际结果并非如此。请问是否可以配置Matplotlib,使其根据轴单位的转换因子自动调整'equal'模式下的宽高比,无需手动计算?

内容的提问来源于stack exchange,提问作者Ray Osborn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 14:13:19