I tried to use widgets by simply displaying a graph depending on checkboxes.
It shows the number of births along the years, for 2 cities (Grenoble and Vizille).
I want to display the evolution lines for 0, 1 or 2 cities depending on checkboxes.
At the beginning it’s ok : it displays 0 lines, and then 1 or 2 when we check the boxes.
But if I uncheck a box, it doesn’t remove a line.
What have I forgotten in my code ?
Here is a reproducible example :
import os
import pandas as pd
import plotly.graph_objects as go
from ipywidgets import widgets
# CSV from URL
url = "https://entrepot.metropolegrenoble.fr/opendata/200040715-MET/insee/etat_civil_200040715.csv"
data_pop = pd.read_csv(url)
# Data prep
noms_col = data_pop.columns
data_pop.reset_index(inplace=True)
data_pop.drop(["code_postal"],axis=1,inplace=True)
data_pop.columns = noms_col
# Using widgets
use_Gre = widgets.Checkbox(
description='Grenoble',
value=False,
)
use_Viz = widgets.Checkbox(
description='Vizille',
value=False,
)
container_1 = widgets.HBox(children=[use_Gre, use_Viz])
g = go.FigureWidget(data=[{'type': 'scatter'}])
def validate1():
if use_Gre.value is True:
return True
else:
return False
def validate2():
if use_Viz.value is True:
return True
else:
return False
def response1(change):
if validate1():
if use_Gre.value:
trace01 = data_pop[data_pop['commune']=="Grenoble"].nombre_naissances
x1=data_pop[data_pop['commune']=="Grenoble"].annee
with g.batch_update():
g.add_scatter(y=trace01,name="Grenoble", x= x1)
def response2(change):
if validate2():
if use_Viz.value:
trace02 = data_pop[data_pop['commune']=="Vizille"].nombre_naissances
x2=data_pop[data_pop['commune']=="Vizille"].annee
with g.batch_update():
g.add_scatter(y=trace02,name="Vizille", x= x2)
use_Gre.observe(response1, names="value")
use_Viz.observe(response2, names="value")
widgets.VBox([container_1, g])