Matplotlib Legend Toggling Tutorial
Tags: python, coding, programming, tutorial
Published: 2024-07-10 03:24:38


## Introduction

![MindMap](https://internal-api-drive-stream.feishu.cn/space/api/box/stream/download/authcode/?code=NDkwNzdjMjhjMmM0MDllYzNjNGJkMjk0YTE5OWEzMTBfMjkzYjI2M2IxMDllYTQzNDVjYjUyMjY1MmY1MjM2NGZfSUQ6NzM4OTg0MjgxMjcwNjcxNzcwMF8xNzIwNTgxODc3OjE3MjA2NjgyNzdfVjM)

This article covers the following tech skills:

![Skills Graph](https://skills-graph.labex.io/python-matplotlib-legend-toggling-tutorial-48802.jpg)

In this lab, we will learn how to enable picking on the legend to toggle the original line on and off using Python Matplotlib.

### VM Tips

After [the VM](https://labex.io/tutorials/python-matplotlib-legend-toggling-tutorial-48802) 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 Required Libraries

First, we need to import the required libraries, which are NumPy and Matplotlib.

```python
import matplotlib.pyplot as plt
import numpy as np
```


## Prepare Data

We will generate two sine waves with different frequencies using NumPy.

```python
t = np.linspace(0, 1)
y1 = 2 * np.sin(2*np.pi*t)
y2 = 4 * np.sin(2*np.pi*2*t)
```


## Create Figure and Axes

We will create a figure and axes using Matplotlib and set the title of the plot.

```python
fig, ax = plt.subplots()
ax.set_title('Click on legend line to toggle line on/off')
```


## Create Lines and Legend

We will create two lines and a legend using Matplotlib.

```python
line1, = ax.plot(t, y1, lw=2, label='1 Hz')
line2, = ax.plot(t, y2, lw=2, label='2 Hz')
leg = ax.legend(fancybox=True, shadow=True)
```


## Map Legend Lines to Original Lines

We will map the legend lines to the original lines using a dictionary.

```python
lines = [line1, line2]
lined = {}  # Will map legend lines to original lines.
for legline, origline in zip(leg.get_lines(), lines):
    legline.set_picker(True)  # Enable picking on the legend line.
    lined[legline] = origline
```


## Define the On Pick Event Function

We will define the on pick event function that will toggle the visibility of the original line corresponding to the legend proxy line.

```python
def on_pick(event):
    # On the pick event, find the original line corresponding to the legend
    # proxy line, and toggle its visibility.
    legline = event.artist
    origline = lined[legline]
    visible = not origline.get_visible()
    origline.set_visible(visible)
    # Change the alpha on the line in the legend, so we can see what lines
    # have been toggled.
    legline.set_alpha(1.0 if visible else 0.2)
    fig.canvas.draw()
```


## Connect the On Pick Event Function to the Canvas

We will connect the on pick event function to the canvas.

```python
fig.canvas.mpl_connect('pick_event', on_pick)
```


## Show the Plot

We will show the plot using Matplotlib.

```python
plt.show()
```


## Summary

In this lab, we learned how to enable picking on the legend to toggle the original line on and off using Python Matplotlib. We created a figure and axes, prepared data, created lines and legend, mapped legend lines to original lines, defined the on pick event function, connected the on pick event function to the canvas, and showed the plot.

---

> 🚀 Practice Now: [Matplotlib Legend Toggling Tutorial](https://labex.io/tutorials/python-matplotlib-legend-toggling-tutorial-48802)

---

## Want to Learn More?

- 🌳 Learn the latest [Python Skill Trees](https://labex.io/skilltrees/python)
- 📖 Read More [Python Tutorials](https://labex.io/tutorials/category/python)
- 💬 Join our [Discord](https://discord.gg/J6k3u69nU6) or tweet us [@WeAreLabEx](https://twitter.com/WeAreLabEx)