'Python subplots with multiple checkboxes? Click event in graphics? How to make?

Does anyone have any idea what tool or library I could use in Python to do the following:

I have several signals in a list, I wanted to plot multiple signal graphs side by side with subplots, and then I wanted to select just some of the plots based on clicks or checkbox selection on top of each one, in the end return the index of all selected ones.

An example would be the code below, but I would change the checkbox selection to get the index instead of changing the graph, but I wanted to do this in several subplots, side by side, so I would need to have a checkbox on each one.

x = np.linspace(0, 5, 100)
y = np.exp(x)
  
# Plotting the graph for exponential function
def plot(checkbox):
      
    # if checkbox is ticked then scatter
    # plot will be displayed
    if checkbox:
        plt.scatter(x, y, s = 5)
        plt.title('Scatter plot of exponential curve')
      
    # if checkbox is not ticked (by default)
    # line plot will be displayed
    else:
        plt.plot(x, y)
        plt.title('Line plot of exponential curve')
          
# calling the interact function        
interact(plot, checkbox = bool())


Solution 1:[1]

You can use the ipywidgets library to do that. See code below using your example:

import matplotlib.pyplot as plt
import numpy as np
import ipywidgets as widgets

x = np.linspace(0, 5, 100)
y = np.exp(x)

checkbox=widgets.Checkbox(value=False,description='Check me',disabled=False,indent=False)
  
# Plotting the graph for exponential function
def plot(checkbox):
      
    # if checkbox is ticked then scatter
    # plot will be displayed
    if checkbox:
        plt.scatter(x, y, s = 5,color='b')
        plt.title('Scatter plot of exponential curve')
      
    # if checkbox is not ticked (by default)
    # line plot will be displayed
    else:
        plt.plot(x, y,color='r')
        plt.title('Line plot of exponential curve')
    plt.show()
widgets.interact(plot, checkbox=checkbox)

And the output gives with checkbox unticked:

enter image description here

and with checkbox ticked:

enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 jylls