Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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
)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
133 views
Welcome To Ask or Share your Answers For Others

1 Answer

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))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...