如何利用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
相关产品推荐
相关产品推荐

