备注
前往末尾 下载完整示例代码。
自定义图表子类#
如果你想改变图形的默认行为,可以向 pyplot.figure 传递一个 Figure 的子类。
此示例定义了一个 Figure 子类 WatermarkFigure,它接受一个额外的参数 watermark 以显示自定义的水印文本。该图形是使用 pyplot.figure 的 FigureClass 参数创建的。额外的 watermark 参数被传递给子类的构造函数。
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.figure import Figure
class WatermarkFigure(Figure):
"""A figure with a text watermark."""
def __init__(self, *args, watermark=None, **kwargs):
super().__init__(*args, **kwargs)
if watermark is not None:
bbox = dict(boxstyle='square', lw=3, ec='gray',
fc=(0.9, 0.9, .9, .5), alpha=0.5)
self.text(0.5, 0.5, watermark,
ha='center', va='center', rotation=30,
fontsize=40, color='gray', alpha=0.5, bbox=bbox)
x = np.linspace(-3, 3, 201)
y = np.tanh(x) + 0.1 * np.cos(5 * x)
plt.figure(FigureClass=WatermarkFigure, watermark='draft')
plt.plot(x, y)

参考文献
以下函数、方法、类和模块的使用在本示例中展示: