Introduction
Matplotlib is a plotting library for the Python programming language and its numerical mathematics extension NumPy. In this tutorial, we will learn how to create a simple legend with Matplotlib.
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 Matplotlib
To use Matplotlib, we need to import it first.
import matplotlib.pyplot as plt
Create a Figure and Axes
We need to create a figure and axes to plot our data.
fig, ax = plt.subplots()
Plot the Data
We can plot our data using the plot() function.
line1, = ax.plot([1, 2, 3], label="Line 1", linestyle='--')
line2, = ax.plot([3, 2, 1], label="Line 2", linewidth=4)
Create the First Legend
We can create a legend for the first line using the legend() function.
first_legend = ax.legend(handles=[line1], loc='upper right')
Add the First Legend
We need to add the first legend to the plot using the add_artist() function.
ax.add_artist(first_legend)
Create the Second Legend
We can create another legend for the second line using the legend() function.
ax.legend(handles=[line2], loc='lower right')
Show the Plot
We can show the plot using the show() function.
plt.show()
Summary
In this tutorial, we learned how to create a simple legend with Matplotlib. We imported Matplotlib, created a figure and axes, plotted the data, and created and added two legends to the plot. Finally, we showed the plot using the show() function.