0

I would like to create a button on a Jupyter Notebook in order to replace the if statement used in the following code:

from ipywidgets import interact
import ipywidgets as widgets
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from IPython.display import display
import scipy as sci

# I create two dataset
x = np.linspace(0, 2*np.pi, 2000)
y1=np.sin(2*x)
y2=np.sin(4*x)
y3=np.sin(8*x)

f1=np.exp(-x**2)
f2=np.exp(-2*x**2)
f3=np.exp(-3*x**2)

ms=[y1,y2,y3]
mt=[f1,f2,f3]
ms=np.transpose(ms)
mt=np.transpose(mt)
dataset_1=pd.DataFrame(ms)
dataset_2=pd.DataFrame(mt)

control=1 # Selection parameter used in the if condition


# This is the condition that I want to replace by a button
if control==1: 
    data=dataset_1
    data.plot()
    plt.show()

elif control==0:
    data=dataset_2
    data.plot()
    plt.show() 

Here I created two dataset composed by three sines and gaussians respectively. I wonder if it is possible to use a radio-button like this:

widgets.RadioButtons(
options=['dataset 1', 'dataset 2'],
description='Switching:',
disabled=False
)
Ben Holland
  • 2,309
  • 4
  • 34
  • 50
A.M
  • 13
  • 4

2 Answers2

1

It is possible you just need to create a simple function with you condition and use interact.

from ipywidgets import interact
import ipywidgets as widgets
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from IPython.display import display
import scipy as sci

# I create two dataset
x = np.linspace(0, 2*np.pi, 2000)
y1=np.sin(2*x)
y2=np.sin(4*x)
y3=np.sin(8*x)

f1=np.exp(-x**2)
f2=np.exp(-2*x**2)
f3=np.exp(-3*x**2)

ms=[y1,y2,y3]
mt=[f1,f2,f3]
ms=np.transpose(ms)
mt=np.transpose(mt)
dataset_1=pd.DataFrame(ms)
dataset_2=pd.DataFrame(mt)


def f(Dataset):
    control = Dataset
    if control == 'dataset 1': 
        data=dataset_1
        data.plot()
        plt.show()

    elif control== 'dataset 2':
        data=dataset_2
        data.plot()
        plt.show() 
    return Dataset


interact(f, Dataset = widgets.RadioButtons(
options=['dataset 1', 'dataset 2'],
description='Switching:',
disabled=False))
It_is_Chris
  • 13,504
  • 2
  • 23
  • 41
0

Yes it is. Create a new cell with the following code:

@interact(control=widgets.RadioButtons(
    options=[1,2],
    description='Dataset'
))
def plot_df(control):
    data = eval('dataset_{}'.format(control))
    data.plot()

enter image description here

jeschwar
  • 1,286
  • 7
  • 10