Add Watermark to Matplotlib Plot

PythonPythonBeginner
Practice Now

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

Introduction

In this lab, we will learn how to add a text watermark effect to a matplotlib 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.

Import Necessary Libraries

Before we start, we need to import the necessary libraries. In this lab, we will be using numpy and matplotlib.

import matplotlib.pyplot as plt
import numpy as np

Generate Data

Let's generate some random data to plot.

## Fixing random state for reproducibility
np.random.seed(19680801)

fig, ax = plt.subplots()
ax.plot(np.random.rand(20), '-o', ms=20, lw=2, alpha=0.7, mfc='orange')
ax.grid()

Add Text Watermark

To add a text watermark, we can use the text() method of the Figure object. We need to provide the position, text, and other properties like font size, color, and transparency.

ax.text(0.5, 0.5, 'created with matplotlib', transform=ax.transAxes,
        fontsize=40, color='gray', alpha=0.5,
        ha='center', va='center', rotation=30)

Display the Plot

Finally, we can display the plot using the show() method.

plt.show()

Summary

In this lab, we learned how to add a text watermark effect to a matplotlib plot. We imported the necessary libraries, generated random data, added the text watermark using the text() method, and displayed the plot using the show() method.

Other Python Tutorials you may like