Matplotlib Legend Toggling Tutorial

PythonPythonBeginner
Practice Now

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

Introduction

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.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/BasicConceptsGroup(["`Basic Concepts`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/PlottingDataGroup(["`Plotting Data`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/PlotCustomizationGroup(["`Plot Customization`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/AdvancedTopicsGroup(["`Advanced Topics`"]) python(("`Python`")) -.-> python/ControlFlowGroup(["`Control Flow`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python(("`Python`")) -.-> python/ModulesandPackagesGroup(["`Modules and Packages`"]) python(("`Python`")) -.-> python/DataScienceandMachineLearningGroup(["`Data Science and Machine Learning`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") matplotlib/BasicConceptsGroup -.-> matplotlib/importing_matplotlib("`Importing Matplotlib`") matplotlib/BasicConceptsGroup -.-> matplotlib/figures_axes("`Understanding Figures and Axes`") matplotlib/PlottingDataGroup -.-> matplotlib/line_plots("`Line Plots`") matplotlib/PlotCustomizationGroup -.-> matplotlib/legend_config("`Legend Configuration`") matplotlib/AdvancedTopicsGroup -.-> matplotlib/event_handling("`Event Handling`") python/BasicConceptsGroup -.-> python/booleans("`Booleans`") python/ControlFlowGroup -.-> python/conditional_statements("`Conditional Statements`") python/ControlFlowGroup -.-> python/for_loops("`For Loops`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/FunctionsGroup -.-> python/function_definition("`Function Definition`") python/ModulesandPackagesGroup -.-> python/importing_modules("`Importing Modules`") 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-48802{{"`Matplotlib Legend Toggling Tutorial`"}} matplotlib/importing_matplotlib -.-> lab-48802{{"`Matplotlib Legend Toggling Tutorial`"}} matplotlib/figures_axes -.-> lab-48802{{"`Matplotlib Legend Toggling Tutorial`"}} matplotlib/line_plots -.-> lab-48802{{"`Matplotlib Legend Toggling Tutorial`"}} matplotlib/legend_config -.-> lab-48802{{"`Matplotlib Legend Toggling Tutorial`"}} matplotlib/event_handling -.-> lab-48802{{"`Matplotlib Legend Toggling Tutorial`"}} python/booleans -.-> lab-48802{{"`Matplotlib Legend Toggling Tutorial`"}} python/conditional_statements -.-> lab-48802{{"`Matplotlib Legend Toggling Tutorial`"}} python/for_loops -.-> lab-48802{{"`Matplotlib Legend Toggling Tutorial`"}} python/lists -.-> lab-48802{{"`Matplotlib Legend Toggling Tutorial`"}} python/tuples -.-> lab-48802{{"`Matplotlib Legend Toggling Tutorial`"}} python/function_definition -.-> lab-48802{{"`Matplotlib Legend Toggling Tutorial`"}} python/importing_modules -.-> lab-48802{{"`Matplotlib Legend Toggling Tutorial`"}} python/numerical_computing -.-> lab-48802{{"`Matplotlib Legend Toggling Tutorial`"}} python/data_visualization -.-> lab-48802{{"`Matplotlib Legend Toggling Tutorial`"}} python/build_in_functions -.-> lab-48802{{"`Matplotlib Legend Toggling Tutorial`"}} end

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.

Other Python Tutorials you may like