Matplotlib 简明教程

Matplotlib - Working With Text

Matplotlib 具有广泛的文本支持,包括:数学表达式的支持、对栅格和矢量输出的支持、任意旋转的新行分隔文本以及 Unicode 支持。Matplotlib 包含其自己的 matplotlib.font_manager,它实现了一个跨平台、符合 W3C 的字体查找算法。

Matplotlib has extensive text support, including support for mathematical expressions, TrueType support for raster and vector outputs, newline separated text with arbitrary rotations, and unicode support. Matplotlib includes its own matplotlib.font_manager which implements a cross platform, W3C compliant font finding algorithm.

用户可以很好地控制文本属性(字体大小、字体粗细、文本位置和颜色等)。Matplotlib 实现了大量的 TeX 数学符号和命令。

The user has a great deal of control over text properties (font size, font weight, text location and color, etc.). Matplotlib implements a large number of TeX math symbols and commands.

以下命令列表用于在 Pyplot 界面中创建文本 -

The following list of commands are used to create text in the Pyplot interface −

text

Add text at an arbitrary location of the Axes.

annotate

Add an annotation, with an optional arrow, at an arbitrary location of theAxes.

xlabel

Add a label to the Axes’s x-axis.

ylabel

Add a label to the Axes’s y-axis.

title

Add a title to the Axes.

figtext

Add text at an arbitrary location of the Figure.

suptitle

Add a title to the Figure.

所有这些函数都创建并返回一个 matplotlib.text.Text() 实例。

All of these functions create and return a matplotlib.text.Text() instance.

以下脚本演示了上述一些函数的使用情况:

Following scripts demonstrate the use of some of the above functions −

import matplotlib.pyplot as plt
fig = plt.figure()

ax = fig.add_axes([0,0,1,1])

ax.set_title('axes title')
ax.set_xlabel('xlabel')
ax.set_ylabel('ylabel')
ax.text(3, 8, 'boxed italics text in data coords', style='italic',
bbox = {'facecolor': 'red'})
ax.text(2, 6, r'an equation: $E = mc^2$', fontsize = 15)
ax.text(4, 0.05, 'colored text in axes coords',
verticalalignment = 'bottom', color = 'green', fontsize = 15)
ax.plot([2], [1], 'o')
ax.annotate('annotate', xy = (2, 1), xytext = (3, 4),
arrowprops = dict(facecolor = 'black', shrink = 0.05))
ax.axis([0, 10, 0, 10])
plt.show()

上述代码行将生成以下输出 −

The above line of code will generate the following output −

working with text