Instagram
youtube
Facebook
Twitter

Create clickable legends.

Description:
This code creates a plot with clickable legends, allowing users to toggle the visibility of each data series by clicking on the legend items.

Code Explanation:

  • First, we import matplotlib for plotting.

  • We create sample data for multiple lines (like product A, B, C).

  • Then we plot each line with a label, which will show in the legend.

  • We use legend = ax.legend() to create a legend and store it in a variable.

  • We make each legend item clickable using legend.set_picker(True) and assign a pick event handler.

  • When a legend item is clicked:

    • The corresponding line's visibility is toggled.

    • The legend item's appearance (like fading out) is also updated to reflect its visibility.

  • This is useful for interactive dashboards or when analyzing multiple data series.


Program:

import matplotlib.pyplot as plt
import numpy as np

# Create sample data
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
y3 = np.sin(x + np.pi / 4)

# Create the plot
fig, ax = plt.subplots()
line1, = ax.plot(x, y1, label='Product A')
line2, = ax.plot(x, y2, label='Product B')
line3, = ax.plot(x, y3, label='Product C')

# Add the legend and make it clickable
legend = ax.legend(loc='upper right')
lines = [line1, line2, line3]
lined = dict()

# Link each legend item to its corresponding line
for legline, origline in zip(legend.get_lines(), lines):
    legline.set_picker(True)
    lined[legline] = origline

# Define what happens when legend is clicked
def on_pick(event):
    legline = event.artist
    origline = lined[legline]
    visible = not origline.get_visible()
    origline.set_visible(visible)
    legline.set_alpha(1.0 if visible else 0.2)
    fig.canvas.draw()

# Connect the pick event to the handler
fig.canvas.mpl_connect('pick_event', on_pick)

# Show the plot
plt.title("Interactive Clickable Legends")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.grid(True)
plt.show()


Output: