Matplotlib Legend Toggling Tutorial

Introduction

This article covers the following tech skills:

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 startup is done,…


This content originally appeared on DEV Community and was authored by Labby

Introduction

MindMap

This article covers the following tech skills:

Skills Graph

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 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.

import matplotlib.pyplot as plt
import numpy as np

Prepare Data

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

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.

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.

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.

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.

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.

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

Show the Plot

We will show the plot using Matplotlib.

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

Want to Learn More?


This content originally appeared on DEV Community and was authored by Labby


Print Share Comment Cite Upload Translate Updates
APA

Labby | Sciencx (2024-07-10T03:24:38+00:00) Matplotlib Legend Toggling Tutorial. Retrieved from https://www.scien.cx/2024/07/10/matplotlib-legend-toggling-tutorial/

MLA
" » Matplotlib Legend Toggling Tutorial." Labby | Sciencx - Wednesday July 10, 2024, https://www.scien.cx/2024/07/10/matplotlib-legend-toggling-tutorial/
HARVARD
Labby | Sciencx Wednesday July 10, 2024 » Matplotlib Legend Toggling Tutorial., viewed ,<https://www.scien.cx/2024/07/10/matplotlib-legend-toggling-tutorial/>
VANCOUVER
Labby | Sciencx - » Matplotlib Legend Toggling Tutorial. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2024/07/10/matplotlib-legend-toggling-tutorial/
CHICAGO
" » Matplotlib Legend Toggling Tutorial." Labby | Sciencx - Accessed . https://www.scien.cx/2024/07/10/matplotlib-legend-toggling-tutorial/
IEEE
" » Matplotlib Legend Toggling Tutorial." Labby | Sciencx [Online]. Available: https://www.scien.cx/2024/07/10/matplotlib-legend-toggling-tutorial/. [Accessed: ]
rf:citation
» Matplotlib Legend Toggling Tutorial | Labby | Sciencx | https://www.scien.cx/2024/07/10/matplotlib-legend-toggling-tutorial/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.