确定 Matplotlib 轴的大小(以像素为单位)

matplotlibserver side programmingprogramming更新于 2025/11/13 18:36:00

要确定轴的大小(以像素为单位),我们可以采取以下步骤 −

  • 使用 subplots() 方法、fig  和 ax 创建一个图形和一组子图。

  • 要获取 DPI,请使用 fig.dpi。 打印详细信息。

  • 在显示框中查找边界框。

  • 使用 bbox.width 和 bbox.height 查找宽度和高度。

  • 打印宽度和高度。

示例

from matplotlib import pyplot as plt

fig, ax = plt.subplots()
print("Dot per inch(DPI) for the figure is: ", fig.dpi)
bbox = ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
width, height = bbox.width, bbox.height
print("Axis sizes are(in pixels):", width, height)

输出

Dot per inch(DPI) for the figure is: 100.0
Axis sizes are(in pixels): 4.96 3.696

相关文章