天天看點

matplotlib之pyplot子產品——添加文本、注解(text、annotate)

概述

text

函數作用是根據

x

y

坐标向圖像添加文本。

annotate

函數作用是根據

x

y

坐标向圖像添加文本注解。

兩者非常相似,但是又有一定差别。

text

函數概述

text

函數的簽名為:

matplotlib.pyplot.text(x, y, s, fontdict=None, **kwargs)

參數說明如下:

  • x

    y

    :放置文本的坐标。浮點數。必備參數。
  • s

    :文本。字元串。必備參數。
  • fontdict

    :字型屬性字典,用于覆寫預設文本的字型屬性。字典。預設值為

    None

    ,應用

    rcParams

    中的字型屬性。可選參數。
  • **kwargs

    Text

    對象的相關屬性。

text

函數的傳回值為

Text

對象。

annotate

函數概述

annotate

函數的簽名為:

matplotlib.pyplot.annotate(text, xy, *args, **kwargs))

參數說明如下:

  • text

    :注解文本。字元串。必備參數。
  • xy

    :需要注解的坐标,使用

    xycoords

    參數确定的坐标系。浮點數元組。必備參數。
  • xycoords

    :設定

    xy

    參數所使用的坐标系。字元串、

    Artist

    Transform

    、可調用對象、

    (float, float)

    。預設值為

    'data'

    ,即被注解對象的坐标系。可選參數。
    說明
    ‘figure points’ 相對于圖像左下角的點數(points)
    ‘figure pixels’ 相對于圖像左下角的像素數(pixels)
    ‘figure fraction’ 相對于圖像左下角的比例((0, 0) 為圖像左下角 (1, 1) 為右上角)
    ‘axes points’ 相對于子圖左下角的點數(points)
    ‘axes pixels’ 相對于子圖左下角的像素數(pixels)
    ‘axes fraction’ 相對于子圖左下角的比例
    ‘data’ 預設值,使用被注解對象的坐标系
    ‘polar’ (theta, r)
  • xytext

    :放置注解文本的坐标。浮點數元組。預設值為

    xy

    。必備參數。
  • textcoords

    :設定

    xytext

    所使用的的坐标系。字元串、

    Artist

    Transform

    、可調用對象、

    (float, float)

    。預設值為

    xycoords

    參數。
    說明
    ‘offset points’

    xy

    參數值的偏移量,機關為點(points)
    ‘offset pixels’

    xy

    參數值的偏移量,機關為像素(pixels)
  • annotation_clip

    :當注解超出子圖區域後是否繪制。布爾值或

    None

    。預設值為

    None

    。可選參數。
    • True

      :隻有當

      xy

      坐标位于子圖之内才繪制注解。
    • False

      :不檢測

      xy

      坐标位置,一直繪制注解。
    • None

      :隻有當

      xy

      坐标位于子圖之内才繪制注解,且

      xycoords

      參數值為

      'data'

  • **kwargs

    Text

    對象的相關屬性。
  • arrowprops

    :被注解坐标點

    xy

    與注解文本位置

    xytext

    之間的箭頭屬性。字典,

    FancyArrowPatch

    對象屬性。預設值為

    None

    ,即不繪制箭頭。可選參數。

    FancyArrowPatch

    相關屬性如下:

text

函數的傳回值為

Annotation

對象。

text

函數和

annotate

函數的對比

根據下面的示例可知:

  • text

    函數可在指定坐标點繪制文本。
  • annotate

    函數如果隻使用

    text

    xy

    參數,那麼功能與

    text

    函數類似。

    但是

    annotate

    函數可以獨立設定注解文本的位置,還可以添加需要注解的資料坐标與注解文本之間的箭頭。
matplotlib之pyplot子產品——添加文本、注解(text、annotate)
import matplotlib.pyplot as plt

plt.xlim(0,5)
plt.ylim(0,5)
# 繪制3個坐标點
plt.plot((3,3,3),(1,2,3),'o')
# 使用text函數設定文本
plt.text(3,1,'text')
# 使用annotate函數必備參數繪制注解
plt.annotate('annotate', xy=(3, 2))
# 使用annotate函數繪制注解,添加訓示箭頭
plt.annotate('annotate', xy=(3, 3), xytext=(4,3),
            arrowprops=dict(arrowstyle='->',facecolor='black')
            )
plt.show()