Creating Custom Figure Subclasses

MatplotlibMatplotlibBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, you will learn how to create custom figure subclasses in Matplotlib. You will create a WatermarkFigure class that adds a text watermark to the plot.

VM Tips

After the VM startup is done, click the top left corner to switch to the Notebook tab to access Jupyter Notebook for practice.

Sometimes, you may need to wait a few seconds for Jupyter Notebook to finish loading. The validation of operations cannot be automated because of limitations in Jupyter Notebook.

If you face issues during learning, feel free to ask Labby. Provide feedback after the session, and we will promptly resolve the problem for you.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python(("`Python`")) -.-> python/FileHandlingGroup(["`File Handling`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/BasicConceptsGroup(["`Basic Concepts`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/PlottingDataGroup(["`Plotting Data`"]) python(("`Python`")) -.-> python/ControlFlowGroup(["`Control Flow`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/ModulesandPackagesGroup(["`Modules and Packages`"]) python(("`Python`")) -.-> python/ObjectOrientedProgrammingGroup(["`Object-Oriented Programming`"]) python(("`Python`")) -.-> python/PythonStandardLibraryGroup(["`Python Standard Library`"]) python(("`Python`")) -.-> python/DataScienceandMachineLearningGroup(["`Data Science and Machine Learning`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") python/FunctionsGroup -.-> python/keyword_arguments("`Keyword Arguments`") python/FileHandlingGroup -.-> python/with_statement("`Using with Statement`") matplotlib/BasicConceptsGroup -.-> matplotlib/importing_matplotlib("`Importing Matplotlib`") matplotlib/BasicConceptsGroup -.-> matplotlib/figures_axes("`Understanding Figures and Axes`") matplotlib/PlottingDataGroup -.-> matplotlib/line_plots("`Line Plots`") python/BasicConceptsGroup -.-> python/variables_data_types("`Variables and Data Types`") python/ControlFlowGroup -.-> python/conditional_statements("`Conditional Statements`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/FunctionsGroup -.-> python/function_definition("`Function Definition`") python/FunctionsGroup -.-> python/default_arguments("`Default Arguments`") python/ModulesandPackagesGroup -.-> python/importing_modules("`Importing Modules`") python/ModulesandPackagesGroup -.-> python/using_packages("`Using Packages`") python/ObjectOrientedProgrammingGroup -.-> python/classes_objects("`Classes and Objects`") python/ObjectOrientedProgrammingGroup -.-> python/constructor("`Constructor`") python/ObjectOrientedProgrammingGroup -.-> python/polymorphism("`Polymorphism`") python/ObjectOrientedProgrammingGroup -.-> python/encapsulation("`Encapsulation`") python/PythonStandardLibraryGroup -.-> python/data_collections("`Data Collections`") python/DataScienceandMachineLearningGroup -.-> python/numerical_computing("`Numerical Computing`") python/DataScienceandMachineLearningGroup -.-> python/data_visualization("`Data Visualization`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") subgraph Lab Skills python/comments -.-> lab-48640{{"`Creating Custom Figure Subclasses`"}} python/keyword_arguments -.-> lab-48640{{"`Creating Custom Figure Subclasses`"}} python/with_statement -.-> lab-48640{{"`Creating Custom Figure Subclasses`"}} matplotlib/importing_matplotlib -.-> lab-48640{{"`Creating Custom Figure Subclasses`"}} matplotlib/figures_axes -.-> lab-48640{{"`Creating Custom Figure Subclasses`"}} matplotlib/line_plots -.-> lab-48640{{"`Creating Custom Figure Subclasses`"}} python/variables_data_types -.-> lab-48640{{"`Creating Custom Figure Subclasses`"}} python/conditional_statements -.-> lab-48640{{"`Creating Custom Figure Subclasses`"}} python/tuples -.-> lab-48640{{"`Creating Custom Figure Subclasses`"}} python/function_definition -.-> lab-48640{{"`Creating Custom Figure Subclasses`"}} python/default_arguments -.-> lab-48640{{"`Creating Custom Figure Subclasses`"}} python/importing_modules -.-> lab-48640{{"`Creating Custom Figure Subclasses`"}} python/using_packages -.-> lab-48640{{"`Creating Custom Figure Subclasses`"}} python/classes_objects -.-> lab-48640{{"`Creating Custom Figure Subclasses`"}} python/constructor -.-> lab-48640{{"`Creating Custom Figure Subclasses`"}} python/polymorphism -.-> lab-48640{{"`Creating Custom Figure Subclasses`"}} python/encapsulation -.-> lab-48640{{"`Creating Custom Figure Subclasses`"}} python/data_collections -.-> lab-48640{{"`Creating Custom Figure Subclasses`"}} python/numerical_computing -.-> lab-48640{{"`Creating Custom Figure Subclasses`"}} python/data_visualization -.-> lab-48640{{"`Creating Custom Figure Subclasses`"}} python/build_in_functions -.-> lab-48640{{"`Creating Custom Figure Subclasses`"}} end

Import necessary libraries

First, import the necessary libraries: matplotlib.pyplot and numpy.

import matplotlib.pyplot as plt
import numpy as np

Create a custom figure subclass

Create a custom figure subclass called WatermarkFigure that adds a text watermark to the plot. This class inherits from the Figure class of Matplotlib.

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)

Create data for the plot

Create some data for the plot. In this example, we will create x and y arrays using the numpy library.

x = np.linspace(-3, 3, 201)
y = np.tanh(x) + 0.1 * np.cos(5 * x)

Plot the data using custom figure subclass

Use the plt.figure() function to plot the data using the custom figure subclass WatermarkFigure. In this example, we will add the watermark text "draft" to the plot.

plt.figure(FigureClass=WatermarkFigure, watermark='draft')
plt.plot(x, y)

Review references

Review the references used in this example.

## References
## matplotlib.pyplot.figure
## matplotlib.figure.Figure
## matplotlib.figure.Figure.text

Summary

In this lab, you learned how to create a custom figure subclass in Matplotlib. You created a WatermarkFigure class that adds a text watermark to the plot. You also learned how to plot data using the custom figure subclass.