Skip to content
Related Articles

Related Articles

Matplotlib – Checkbox Widget
  • Last Updated : 24 Feb, 2021

In this article, We are going to see the use of these checkboxes in matplotlib plots to make our plot more interactive. Checkbox widget offers us the freedom to make our plot more interactive. By using checkboxes we can perform on-tick events which on ticking the checkbox will trigger some event.

We will use the interact() function in ipywidgets library, to create checkboxes. The interact function automatically creates user interface (UI) controls for exploring code and data interactively. It accepts two parameters; a custom function and a Boolean keyword argument using which it generates autogenerate UI controls for a checkbox.

Approach:

We will be plotting the graph of the exponential curve in a range of (0,5). For that, we’ve created a hundred points (x-values) in the range 0-5 and then generate its corresponding exponential value using the NumPy.exp() function. As discussed earlier, Now created a custom function named plot() which accepts the Boolean value passed in the interact() function. Based upon the Boolean value either True or False, the checkbox is triggered.

When the passed parameter is set to False, then the checkbox is not clicked by default and a simple line plot of the exponential curve will be displayed. When the passed parameter is set to True, then the checkbox is clicked, and the scatter plot of the exponential curve gets displayed.



Code:

Python




import numpy as np
import matplotlib.pyplot as plt
from ipywidgets import interact
%matplotlib inline
  
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())

Output:

When the checkbox is not clicked by default Boolean value is set to False and the line plot will be displayed.

Checkbox not ticked: line plot

When the checkbox is ticked Boolean value inside the interact() function is set to True and a scatter plot will be displayed.

checkbox ticked: scatter plot


Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :