天天看点

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()