Skip to content
Snippets Groups Projects
Verified Commit 127d47ed authored by David Beniamine's avatar David Beniamine
Browse files

More examples

parent ba32660b
No related branches found
No related tags found
No related merge requests found
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Interactive sliders ## Interactive sliders
Les sliders affectent le calcul, la valeur est calulée par un callback python Les sliders affectent le calcul, la valeur est calulée par un callback python
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
from ipywidgets import HBox, VBox, IntSlider, interactive_output, Dropdown from ipywidgets import HBox, VBox, IntSlider, interactive_output, Dropdown
from IPython.display import display from IPython.display import display
a = IntSlider() a = IntSlider()
b = IntSlider() b = IntSlider()
def f(a, b): def f(a, b):
print("{} * {} = {}".format(a, b, a * b)) print("{} * {} = {}".format(a, b, a * b))
out = interactive_output(f, { "a": a, "b": b }) out = interactive_output(f, { "a": a, "b": b })
display(HBox([VBox([a, b]), out])) display(HBox([VBox([a, b]), out]))
``` ```
%% Output %% Output
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
Un autre slider, pas de calcul Un autre slider, pas de calcul
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
from ipywidgets import interact from ipywidgets import interact
def foo(x): def foo(x):
print(x) print(x)
interact(foo, x=(0, 10)) interact(foo, x=(0, 10))
``` ```
%% Output %% Output
<function __main__.foo(x)> <function __main__.foo(x)>
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Quand on click ce boutton un affichage ce produit ## Quand on click ce boutton un affichage ce produit
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# sort of based on https://github.com/voila-dashboards/voila-material/issues/18 # sort of based on https://github.com/voila-dashboards/voila-material/issues/18
import ipywidgets as widgets import ipywidgets as widgets
from IPython.display import display from IPython.display import display
output = widgets.Output() output = widgets.Output()
@output.capture(clear_output=False,wait=True) # based on https://github.com/jupyter-widgets/ipywidgets/issues/1846 and https://ipywidgets.readthedocs.io/en/latest/examples/Output%20Widget.html @output.capture(clear_output=False,wait=True) # based on https://github.com/jupyter-widgets/ipywidgets/issues/1846 and https://ipywidgets.readthedocs.io/en/latest/examples/Output%20Widget.html
def sayHello(b): def sayHello(b):
print('Hello world!') print('Hello world!')
run_button = widgets.Button( run_button = widgets.Button(
description = 'run' description = 'run'
) )
run_button.on_click(sayHello) run_button.on_click(sayHello)
display(run_button) display(run_button)
output output
``` ```
%% Output %% Output
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Figure interactive avec matplotlib ## Figure interactive avec matplotlib
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
%matplotlib inline %matplotlib inline
from ipywidgets import interact, interactive from ipywidgets import interact, interactive
import matplotlib.pyplot as plt import matplotlib.pyplot as plt
import numpy as np import numpy as np
def ma_fonction(a,b,c): def ma_fonction(a,b,c):
plt.figure(2) # ??? plt.figure(2) # ???
x = np.linspace(-10,10, num=1000) x = np.linspace(-10,10, num=1000)
plt.plot(x, a*x**2+b*x+c) plt.plot(x, a*x**2+b*x+c)
plt.ylim(-10,10) plt.ylim(-10,10)
plt.show() plt.show()
interactive_plot = interactive(ma_fonction, a=(-10,10), b=(-20,20), c=(-5,5)) interactive_plot = interactive(ma_fonction, a=(-10,10), b=(-20,20), c=(-5,5))
interactive_plot interactive_plot
``` ```
%% Output %% Output
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Figure interactive avec seaborn ## Figure interactive avec seaborn
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
from ipywidgets import interact, interactive from ipywidgets import interact, interactive
import matplotlib.pyplot as plt import matplotlib.pyplot as plt
import numpy as np import numpy as np
import seaborn as sns import seaborn as sns
# Chargement d'un dataset connu # Chargement d'un dataset connu
tips = sns.load_dataset("tips") tips = sns.load_dataset("tips")
tips tips
@interact(xmax=50,ymax=10, hue=["smoker","sex","day","time","size"], comic=[('Non',False),('Oui',True)]) @interact(xmax=50,ymax=10, hue=["smoker","sex","day","time","size"], comic=[('Non',False),('Oui',True)])
def f(xmax, ymax, hue, comic): def f(xmax, ymax, hue, comic):
sns.set() sns.set()
sns.set(style="darkgrid") sns.set(style="darkgrid")
if(comic): if(comic):
ctx = plt.xkcd() ctx = plt.xkcd()
else: else:
from contextlib import nullcontext from contextlib import nullcontext
ctx = nullcontext() ctx = nullcontext()
with ctx: with ctx:
plot = sns.relplot(x="total_bill", y="tip", hue=hue, data=tips) plot = sns.relplot(x="total_bill", y="tip", hue=hue, data=tips)
plot.set(xlim=(0, xmax), ylim=(0, ymax)) plot.set(xlim=(0, xmax), ylim=(0, ymax))
``` ```
%% Output %% Output
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Figure interactive avec bokeh ## Figure interactive avec bokeh
Si l'on veut utiliser Bokeh, les choses se complique : Si l'on veut utiliser Bokeh, les choses se complique :
+ L'interaction avec ipywidget ne fonctionne pas sur voilà aucun affichage + L'interaction avec ipywidget ne fonctionne pas sur voilà aucun affichage
+ L'interaction "Bokeh" standard fonctionne sur jupyterlab mais affiche `JavaScript output is disabled in JupyterLab` sur voilà, voir [#108](https://github.com/voila-dashboards/voila/issues/108) + L'interaction "Bokeh" standard fonctionne sur jupyterlab mais affiche `JavaScript output is disabled in JupyterLab` sur voilà, voir [#108](https://github.com/voila-dashboards/voila/issues/108)
+ L'interaction en mode bokeh [app embarquée](https://github.com/bokeh/bokeh/blob/2.2.3/examples/howto/server_embed/notebook_embed.ipynb), fonctionne sur jupyter et voilà embarqué dans jupyter mais demande ouvre une websocket sur un port indeterminé => l'enfer pour le reverse proxy + L'interaction en mode bokeh [app embarquée](https://github.com/bokeh/bokeh/blob/2.2.3/examples/howto/server_embed/notebook_embed.ipynb), fonctionne sur jupyter et voilà embarqué dans jupyter mais demande ouvre une websocket sur un port indeterminé => l'enfer pour le reverse proxy
**Finalement [#244](https://github.com/voila-dashboards/voila/issues/244#issuecomment-514341910) done la solution : embarquer le code bokeh dans [panel holoviz](https://panel.holoviz.org/user_guide/index.html)** **Finalement [#244](https://github.com/voila-dashboards/voila/issues/244#issuecomment-514341910) done la solution : embarquer le code bokeh dans [panel holoviz](https://panel.holoviz.org/user_guide/index.html)**
Cela signifie qu'on utilise l'[interaction de panel](https://panel.holoviz.org/user_guide/Interact.html) Cela signifie qu'on utilise l'[interaction de panel](https://panel.holoviz.org/user_guide/Interact.html)
Voici un exemple "simple" Voici un exemple "simple" inspiré [de celui-ci](https://panel.holoviz.org/gallery/simple/iris_kmeans.html#simple-gallery-iris-kmeans)
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
import panel as pn import panel as pn
# We use interact and widgets from panel # We use interact and widgets from panel
from panel import interact from panel import interact
from panel.widgets import IntSlider from panel.widgets import IntSlider
from bokeh.sampledata.sea_surface_temperature import sea_surface_temperature from bokeh.sampledata.sea_surface_temperature import sea_surface_temperature
from bokeh.models import ColumnDataSource from bokeh.models import ColumnDataSource
from bokeh.plotting import figure from bokeh.plotting import figure
# Use ipywidget communication, required for voilà only required once per notebook # Use ipywidget communication, required for voilà only required once per notebook
pn.extension(comms='ipywidgets') pn.extension(comms='ipywidgets')
``` ```
%% Output %% Output
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# Donnees templates bokeh # Donnees templates bokeh
df = sea_surface_temperature.copy() df = sea_surface_temperature.copy()
# Un slider pour l'interaction # Un slider pour l'interaction
days=IntSlider(name='Smooting by N Days', start=0, end=30, step=1, value=0) days=IntSlider(name='Smooting by N Days', start=0, end=30, step=1, value=0)
@pn.depends(days.param.value) @pn.depends(days.param.value)
def getplot(days): def getplot(days):
if (days): if (days):
data = df.rolling('{0}D'.format(days)).mean() data = df.rolling('{0}D'.format(days)).mean()
else: else:
data = df data = df
source = ColumnDataSource(data=data) source = ColumnDataSource(data=data)
plot = figure(x_axis_type='datetime', y_range=(0, 25), plot = figure(x_axis_type='datetime', y_range=(0, 25),
y_axis_label='Temperature (Celsius)', y_axis_label='Temperature (Celsius)',
title="Sea Surface Temperature at 43.18, -70.43") title="Sea Surface Temperature at 43.18, -70.43")
plot.line('time', 'temperature', source=source) plot.line('time', 'temperature', source=source)
return plot return plot
pn.Column( pn.Column(
days, days,
getplot getplot
).servable() ).servable()
``` ```
%% Output %% Output
Column Column
[0] IntSlider(end=30, name='Smooting by N Days', value_throttled=0) [0] IntSlider(end=30, name='Smooting by N Days', value_throttled=0)
[1] ParamFunction(function) [1] ParamFunction(function)
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
``` ```
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment