注意
前往末尾下載完整範例程式碼。
自訂圖形子類別#
如果您想要變更圖形的預設行為,您可以將 Figure
子類別傳遞至 pyplot.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)

參考文獻
此範例中顯示以下函數、方法、類別和模組的使用