I am working to a plot in matplotlib where multiple lines are represented by a single entry. In particular deselect or select multiple lines when picking a single legend entry; for clarity I started from the demo in matplotlib documentation (https://matplotlib.org/gallery/widgets/check_buttons.html and https://matplotlib.org/api/widgets_api.html#matplotlib.widgets.CheckButtons) and I just modified it a little:
%matplotlib notebook
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import CheckButtons
t = np.arange(0.0, 2.0, 0.01)
s0 = np.sin(2*np.pi*t)
s1 = np.sin(4*np.pi*t)
s2 = np.sin(6*np.pi*t)
s3 = 2*np.sin(4*np.pi*t)
fig, ax = plt.subplots()
l0, = ax.plot(t, s0, lw=2,c='r')
l1, = ax.plot(t, s1, lw=2,c='b')
l2, = ax.plot(t, s2, lw=2,c='g')
l3, = ax.plot(t, s3, lw=2,c='b')
plt.subplots_adjust(left=0.2)
rax = plt.axes([0.05, 0.4, 0.1, 0.15])
check = CheckButtons(rax, ('2 Hz', '4 Hz', '6 Hz'), (True, True, True))
#Define colours for rectangles and set them
c = ['r', 'b', 'g']
[rec.set_facecolor(c[i]) for i, rec in enumerate(check.rectangles)]
def func(label):
if label == '2 Hz':
l0.set_visible(not l0.get_visible())
elif label == '4 Hz':
l1.set_visible(not l1.get_visible())
l3.set_visible(not l3.get_visible())
elif label == '6 Hz':
l2.set_visible(not l2.get_visible())
plt.draw()
check.on_clicked(func)
plt.show()
The output is this:
I would like to solve two kind of problems:
- I don't know how to loop for creating the "lx," values (I have many lines to create and I don't want to write "l0," "l1," "l2," ... etc)
- I would like to having different appearence on checkbutton. In particular I would love to have a rectangle filled with line color when selected, and an empty rectangle (white background) when de-selected.
I tried finding for help in the documentation, but I'm a newbie and I am stuck at the moment. Could someone please help me?
Thank you

