如何在 Matplotlib 中獲取軸上單一單位長度?


要在 Matplotlib 中獲取軸上單一單位長度,我們可以執行以下步驟 -

  • 設定影像尺寸並調整子圖之間和周圍的填充。
  • 使用 numpy 建立xy 資料點。
  • 使用figure() 方法建立新影像或啟用現有影像。
  • '~.axes.Axes' 作為子圖排列的一部分新增到影像中。
  • 使用plot() 方法繪製xy 資料點。
  • 要獲取單一單位長度,請使用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("Vertical length:", xy[0][1])
print("Horizontal length: ", xy[1][0])

plt.show()

輸出

除了圖表,我們還將在控制檯上獲得以下輸出 -

Vertical length: 269.5
Horizontal length: 581.25

更新於:2021 年 7 月 7 日

375 次瀏覽

開啟您的 職業生涯

完成課程獲得認證

入門
廣告
© . All rights reserved.