|
1 | 1 | """
|
2 |
| -=================== |
3 |
| -Custom Figure Class |
4 |
| -=================== |
| 2 | +======================== |
| 3 | +Custom Figure subclasses |
| 4 | +======================== |
5 | 5 |
|
6 |
| -You can pass a custom Figure constructor to figure if you want to derive from |
7 |
| -the default Figure. This simple example creates a figure with a figure title. |
| 6 | +You can pass a `.Figure` subclass to `.pyplot.figure` if you want to change |
| 7 | +the default behavior of the figure. |
| 8 | +
|
| 9 | +This example defines a `.Figure` subclass ``WatermarkFigure`` that accepts an |
| 10 | +additional parameter ``watermark`` to display a custom watermark text. The |
| 11 | +figure is created using the ``FigureClass`` parameter of `.pyplot.figure`. |
| 12 | +The additional ``watermark`` parameter is passed on to the subclass |
| 13 | +constructor. |
8 | 14 | """
|
9 | 15 |
|
10 | 16 | import matplotlib.pyplot as plt
|
11 | 17 | from matplotlib.figure import Figure
|
| 18 | +import numpy as np |
| 19 | + |
12 | 20 |
|
| 21 | +class WatermarkFigure(Figure): |
| 22 | + """A figure with a text watermark.""" |
13 | 23 |
|
14 |
| -class MyFigure(Figure): |
15 |
| - def __init__(self, *args, figtitle='hi mom', **kwargs): |
16 |
| - """ |
17 |
| - custom kwarg figtitle is a figure title |
18 |
| - """ |
| 24 | + def __init__(self, *args, watermark=None, **kwargs): |
19 | 25 | super().__init__(*args, **kwargs)
|
20 |
| - self.text(0.5, 0.95, figtitle, ha='center') |
| 26 | + |
| 27 | + if watermark is not None: |
| 28 | + bbox = dict(boxstyle='square', lw=3, ec='gray', |
| 29 | + fc=(0.9, 0.9, .9, .5), alpha=0.5) |
| 30 | + self.text(0.5, 0.5, watermark, |
| 31 | + ha='center', va='center', rotation=30, |
| 32 | + fontsize=40, color='gray', alpha=0.5, bbox=bbox) |
| 33 | + |
| 34 | + |
| 35 | +x = np.linspace(-3, 3, 201) |
| 36 | +y = np.tanh(x) + 0.1 * np.cos(5 * x) |
| 37 | + |
| 38 | +plt.figure(FigureClass=WatermarkFigure, watermark='draft') |
| 39 | +plt.plot(x, y) |
21 | 40 |
|
22 | 41 |
|
23 |
| -fig = plt.figure(FigureClass=MyFigure, figtitle='my title') |
24 |
| -ax = fig.subplots() |
25 |
| -ax.plot([1, 2, 3]) |
| 42 | +############################################################################# |
| 43 | +# |
| 44 | +# ------------ |
| 45 | +# |
| 46 | +# References |
| 47 | +# """""""""" |
| 48 | +# |
| 49 | +# The use of the following functions, methods, classes and modules is shown |
| 50 | +# in this example: |
26 | 51 |
|
27 |
| -plt.show() |
| 52 | +import matplotlib |
| 53 | +matplotlib.pyplot.figure |
| 54 | +matplotlib.figure.Figure |
| 55 | +matplotlib.figure.Figure.text |
0 commit comments