如何在 Matplotlib 中获取轴上单个单位的长度?

pythonserver side programmingprogramming更新于 2025/8/7 17:16:17

要获取 Matplotlib 中轴上单个单位的长度,我们可以采取以下步骤 −

  • 设置图形大小并调整子图之间和周围的填充。
  • 使用 numpy 创建 x 和 y 数据点。
  • 使用 figure() 方法创建新图形或激活现有图形。
  • 将 '~.axes.Axes' 添加到图形作为子图排列的一部分。
  • 使用 plot() 方法绘制 x 和 y 数据点。
  • 要获取单个单位长度,请使用transData 变换。
  • 打印水平和垂直长度。
  • 要显示图形,请使用 show() 方法。

示例

import numpy as np
import matplotlib.pyplot as plt

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

x = np.arange(0, 10, 0.005)
y = np.exp(-x / 2.) * np.sin(2 * np.pi * x)

fig = plt.figure()

ax = fig.add_subplot(111)
ax.plot(x, y)

xy = ax.transData.transform([(0, 1), (1, 0)])\
    -ax.transData.transform((0, 0))

print("垂直长度:", xy[0][1])

print("水平长度:", xy[1][0])

plt.show()

输出

除了绘图之外,我们还将在控制台上获得以下输出 −

垂直长度:269.5
水平长度:581.25

相关文章


有用资源