Matplotlib - 錨定藝術家



在 Matplotlib 中,**藝術家 (Artist)** 是一個基本物件,它表示繪圖中幾乎所有元件。無論是線條、文字、軸還是任何其他圖形元素,Matplotlib 繪圖中的所有內容都是藝術家 (Artist) 的例項或派生自藝術家 (Artist) 類。

**錨定藝術家 (Anchored Artists)** 是一種特殊的自定義藝術家,可以錨定到繪圖上的特定位置。它們可用於添加註釋、箭頭和其他錨定到特定點或區域的自定義元素。

請參閱以下示例以供參考 -

Anchored Artists_intro

在上圖中,您可以觀察到文字框、圓形和尺寸條都錨定在繪圖上的特定位置。

Matplotlib 中的錨定藝術家

在 Matplotlib 中有兩個模組提供錨定藝術家,它們是 -

  • Matplotlib.offsetbox

  • Mpl_toolkits.axes_grid1.anchored_artists

matplotlib.offsetbox 模組

此模組提供諸如 **AnchoredOffsetbox** 和 **AnchoredText** 之類的類,允許您相對於父軸或特定錨點錨定任意藝術家或文字。這些可用於更通用的註釋和裝飾。

示例

現在,讓我們使用 **matplotlib.offsetbox** 模組中的 **AnchoredText** 類在繪圖上的特定位置實現兩個**錨定文字框**。

import matplotlib.pyplot as plt
from matplotlib.offsetbox import AnchoredText

# Create a figure and axis
fig, ax = plt.subplots(figsize=(7, 4))

# Anchored Text Box 1
at = AnchoredText("Anchored text-box 1",
   loc='upper left', prop=dict(size=10), frameon=True)
at.patch.set_boxstyle("round,pad=0.,rounding_size=0.2")
ax.add_artist(at)

# Anchored Text Box 2
at2 = AnchoredText("Anchored text-box 2",
   loc='center', prop=dict(size=16), frameon=True,
   bbox_to_anchor=(0.5, 0.5),
   bbox_transform=ax.transAxes)
at2.patch.set_boxstyle("round,pad=0.,rounding_size=0.5")
ax.add_artist(at2)

# Display the plot
plt.show()
輸出

執行上述程式碼後,我們將獲得以下輸出 -

Anchored Artists Example 1

mpl_toolkits.axes_grid1.anchored_artists 模組

此模組提供諸如 **AnchoredDirectionArrows**、**AnchoredAuxTransformBox**、**AnchoredDrawingArea** 和 **AnchoredSizeBar** 之類的專用錨定藝術家。每個類用於不同的目的。

讓我們看看每個類的用法 -

  • **AnchoredAuxTransformBox** - 一個帶有轉換座標的錨定容器。

  • **AnchoredDirectionArrows** - 繪製兩個垂直箭頭以指示方向。

  • **AnchoredDrawingArea** - 一個具有固定大小和可填充 DrawingArea 的錨定容器。

  • **AnchoredSizeBar** - 繪製一個水平比例尺,下方帶有居中對齊的標籤。

示例

此示例演示瞭如何使用 AnchoredDirectionArrows 類向 Matplotlib 繪圖新增視覺上吸引人的錨定方向箭頭。

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.font_manager as fm
from mpl_toolkits.axes_grid1.anchored_artists import AnchoredDirectionArrows

np.random.seed(19680801)

fig, ax = plt.subplots(figsize=(7, 4))
ax.imshow(np.random.random((10, 10)))

# Rotated arrow
fontprops = fm.FontProperties(family='serif')

rotated_arrow = AnchoredDirectionArrows(
   ax.transAxes,
   '30', '120',
   loc='center',
   color='w',
   angle=30,
   fontproperties=fontprops
)
ax.add_artist(rotated_arrow)

plt.show()
輸出

執行上述程式碼後,我們將獲得以下輸出 -

Anchored Artists Example 2
廣告