Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
143 views
in Technique[技术] by (71.8m points)

python - Data selection using a button

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

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...