matplotlib之pyplot模块添加文本、注解(text和annotate)

  

当在绘图过程中需要添加文本或者注解时,可以使用matplotlib库的pyplot模块的text()和annotate()方法。下面是详细的攻略过程:

1. 添加文本

1.1 text()方法

text()方法用来在图表中的指定位置添加文字信息。其基本语法如下:

import matplotlib.pyplot as plt
plt.text(x, y, s)

其中,

  • x表示添加的文字所在的横坐标值;
  • y表示添加的文字所在的纵坐标值;
  • s表示添加的文字内容。

下面是一个简单的例子:

import matplotlib.pyplot as plt

plt.plot([1, 2, 3, 4], [1, 4, 2, 3])
plt.text(2, 3, 'This is the top')
plt.show()

上述代码绘制了一个简单的折线图,并在坐标轴上添加了一条文字信息“this is the top”。

1.2 text()方法其他参数说明

text()方法支持多种参数设置,除了几个基本参数外,其他参数均为可选参数。下面对常用的其他参数进行说明。

  • fontsize:字体大小
  • color:字体颜色
  • verticalalignment(va):垂直对齐方式,默认值为'middle',可以设置为'top'、'center'或'bottom'
  • horizontalalignment(ha):水平对齐方式,默认值为'center',可以设置为'left'、'center'或'right'
import matplotlib.pyplot as plt

plt.plot([1, 2, 3, 4], [1, 4, 2, 3])
plt.text(2, 3, 'This is the top', fontsize=10, color='red', ha='center', va='bottom')
plt.show()

1.3 annotate()方法

annotate()方法可用于在图表中的指定位置添加注释。其基本语法如下:

import matplotlib.pyplot as plt
plt.annotate(s, xy, xytext, arrowprops)

其中,

  • s为注释的文本内容;
  • xy为被注释的坐标点,一个元组,格式为(x, y);
  • xytext为注释文本的位置,一个元组,格式为(x, y);
  • arrowprops为箭头属性,一个字典类型。支持多种属性
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10*np.pi, 1000)
y = np.sin(x)

plt.plot(x, y)
plt.annotate('This is the point', xy=(np.pi/2, 1), xytext=(np.pi/2, 1.5), arrowprops=dict(facecolor='black', shrink=0.1))
plt.show()

2. 示例说明

2.1 标注最大值所在点

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 2 * np.pi, 100)
y = np.sin(x)

fig, ax = plt.subplots()
ax.plot(x, y)

xmax = x[np.argmax(y)]
ymax = np.max(y)

ax.annotate(f'Max value: {ymax}',
            xy=(xmax, ymax),
            xycoords='data',
            xytext=(xmax, ymax + 0.5),
            fontsize=12,
            color='r',
            ha='center',
            arrowprops=dict(arrowstyle='->', connectionstyle='arc3', color='r'))

plt.show()

在这个示例中,我们绘制了一个简单的sin函数图像,并标注了函数最大值所在点的坐标及具体数值信息。需要注意的是,注释文本的位置xytext anotated 由最大坐标的x和y再加上一定的距离。箭头样式和颜色也是可以定制的。

2.2 在森林状图上标注各树的高度

import pandas as pd
import matplotlib.pyplot as plt

data = pd.read_csv('forest.csv')
species = data['species']
heights = data['height']

fig, ax = plt.subplots()
bars = ax.bar(species, heights)

for i, bar in enumerate(bars):
    ax.text(bar.get_x() + bar.get_width() / 2, bar.get_height() + 0.05, heights[i], ha='center', fontsize=10)

plt.show()

在这个示例中,我们绘制了一个森林状图,标注了各树的高度。需要注意的是,注释文本的位置xytext是每个树木顶部的坐标加上一定高度,以便使注释信息与柱状图尽量靠近。为了防止注释信息重叠,我们可以通过get_x()get_width()方法来获取每个柱状图的位置和宽度。

相关文章