{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "\n# Custom Figure subclasses\n\nYou can pass a `.Figure` subclass to `.pyplot.figure` if you want to change\nthe default behavior of the figure.\n\nThis example defines a `.Figure` subclass ``WatermarkFigure`` that accepts an\nadditional parameter ``watermark`` to display a custom watermark text. The\nfigure is created using the ``FigureClass`` parameter of `.pyplot.figure`.\nThe additional ``watermark`` parameter is passed on to the subclass\nconstructor.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import matplotlib.pyplot as plt\nimport numpy as np\n\nfrom matplotlib.figure import Figure\n\n\nclass WatermarkFigure(Figure):\n \"\"\"A figure with a text watermark.\"\"\"\n\n def __init__(self, *args, watermark=None, **kwargs):\n super().__init__(*args, **kwargs)\n\n if watermark is not None:\n bbox = dict(boxstyle='square', lw=3, ec='gray',\n fc=(0.9, 0.9, .9, .5), alpha=0.5)\n self.text(0.5, 0.5, watermark,\n ha='center', va='center', rotation=30,\n fontsize=40, color='gray', alpha=0.5, bbox=bbox)\n\n\nx = np.linspace(-3, 3, 201)\ny = np.tanh(x) + 0.1 * np.cos(5 * x)\n\nplt.figure(FigureClass=WatermarkFigure, watermark='draft')\nplt.plot(x, y)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ ".. admonition:: References\n\n The use of the following functions, methods, classes and modules is shown\n in this example:\n\n - `matplotlib.pyplot.figure`\n - `matplotlib.figure.Figure`\n - `matplotlib.figure.Figure.text`\n\n.. tags::\n\n component: figure\n plot-type: line\n level: intermediate\n purpose: showcase\n\n" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.13.2" } }, "nbformat": 4, "nbformat_minor": 0 }