在 Matplotlib 中繪製兩條線之間角度的最佳方法


在 Matplotlib 中,繪製兩條線之間角度的最佳方法是使用Arc類建立角度弧來繪製之間的角度。

步驟

  • 設定圖形大小並調整子圖之間和周圍的填充。
  • 使用figure()方法建立一個新圖形或啟用一個現有圖形。
  • 使用add_subplot()方法將'~.axes.Axes'作為子圖佈局的一部分新增到圖形中。
  • 將二維線例項建立為l1 l2
  • 將線新增到當前座標系。
  • 要繪製角度,呼叫返回橢圓弧的使用者定義方法。弧長可以使用線的斜率建立。
  • 使用add_patch()方法新增一個圖形,即 arc
  • 使用show()方法來顯示圖形。

示例

from matplotlib import pyplot as plt, patches
import math

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

def angle_plot(line1, line2, offset=1.0, color=None, origin=(0, 0),
len_x_axis=1, len_y_axis=1):
   xy1 = line1.get_xydata()
   xy2 = line2.get_xydata()
   slope1 = (xy1[1][1] - xy1[0][1]) / float(xy1[1][0] - xy1[0][0])
   angle1 = abs(math.degrees(math.atan(slope1)))
   slope2 = (xy2[1][1] - xy2[0][1]) / float(xy2[1][0] - xy2[0][0])
   angle2 = abs(math.degrees(math.atan(slope2)))
   theta1 = min(angle1, angle2)
   theta2 = max(angle1, angle2)
   angle = theta2 - theta1
   if color is None:
      color = line1.get_color()

   return patches.Arc(origin, len_x_axis * offset, len_y_axis * offset, 0, theta1, theta2, color=color, label=str(angle) + u"\u00b0")

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)

l1 = plt.Line2D([0, 1], [0, 4], linewidth=1, linestyle="-", color="green")
l2 = plt.Line2D([0, 4.5], [0, 3], linewidth=1, linestyle="-", color="red")

ax.add_line(l1)
ax.add_line(l2)

angle = angle_plot(l1, l2, 0.25)
ax.add_patch(angle)

plt.show()

輸出

更新於:03-Jun-2021

2K+ 瀏覽

開啟您的 職業

透過完成該課程獲得認證

開始
廣告