Matplotlib - 箭頭



什麼是 Matplotlib 中的箭頭?

在 Matplotlib 庫中,箭頭指的是用於指示方向、點之間的連線以及突出顯示繪圖中特定特徵的圖形元素。可以使用plt.arrow()函式將箭頭新增到繪圖中,或者透過使用plt.annotate()函式將其整合到註釋中。

Matplotlib 庫中的箭頭是多功能的元素,用於直觀地描繪視覺化中的方向性、連線或突出顯示,從而幫助更好地傳達資訊。我們可以調整諸如座標、長度、顏色和樣式等引數以滿足特定的視覺化需求。

matplotlib 庫中的plt.arrow()函式在繪圖上的兩點之間建立箭頭。

語法

以下是plt.arrow()函式的語法和引數。

plt.arrow(x, y, dx, dy, kwargs)

其中,

  • x, y - 這些是箭頭的起始點座標。

  • dx, dy - 這些是箭頭在 x 和 y 方向上的長度。

  • kwargs - 我們可以新增其他關鍵字引數來自定義箭頭屬性,例如顏色、寬度、樣式等。

向線形圖新增箭頭

在這個例子中,我們透過使用plt.arrow()函式在繪圖上的給定兩點之間建立箭頭來繪製一個繪圖。我們向此函式傳遞了 x、y、dx 和 dy 點作為輸入引數,用於在這些提到的點建立箭頭。此外,我們還傳遞了諸如箭頭的長度、寬度和顏色等引數。

示例

import matplotlib.pyplot as plt
# Creating a line plot
plt.plot([0, 1], [0, 1])
# Adding an arrow
plt.arrow(0.2, 0.2, 0.4, 0.4, head_width=0.05, head_length=0.1, fc='red', ec='blue')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Arrow created by using plt.arrow() function')
# show grid of the plot
plt.grid(True)
plt.show()
輸出
Matplolib Arrows

單獨新增箭頭

這是建立箭頭的另一個示例。眾所周知,箭頭也可以透過指定arrowprops來定義箭頭樣式,從而整合到plt.annotate()中的註釋中。在這個例子中,'箭頭註釋'連線到點(0.5, 0.5),並使用arrowprops指定箭頭樣式。

示例

import matplotlib.pyplot as plt
# Creating a plot
plt.plot([0, 1], [0, 1])
# Adding an arrow with annotation
plt.annotate('Arrow Annotation', xy=(0.5, 0.5), xytext=(0.2, 0.2), arrowprops=dict(facecolor='yellow',ec = 'red', arrowstyle='->'))
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Arrow Annotation Example')
# Displaying the grid
plt.grid(True)
plt.show()
輸出
Arrow Annotation

在技術圖紙中繪製距離箭頭

為了在 matplotlib 中的技術圖紙中繪製距離箭頭,我們可以使用帶有箭頭屬性的 annotate() 方法。

示例

from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
plt.axhline(3.5)
plt.axhline(2.5)
plt.annotate(
   '', xy=(0.5, 3.5), xycoords='data',
   xytext=(0.5, 2.5), textcoords='data',
   arrowprops={'arrowstyle': '<->'})
plt.annotate(
   '$\it{d=1}$', xy=(0.501, 3.0), xycoords='data',
   xytext=(0.5, 3.5), textcoords='offset points')
plt.show()
輸出
Arrow Annotation
廣告

© . All rights reserved.