Hi everyone,
I’m trying to create a dashboard that after selecting a city from the dropdown options, and then pressing the ADD A CITY, the following behavior should be expected:
- a new closable button appears next to the dropdown menu, and
- the corresponding plot should appear in the figure.
What I want is something similar to the following sketch
The code is given below
import pandas as pd
import numpy as np
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Output, Input
import plotly.graph_objs as go
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
# Generate data
cities = ["Montreal", "Toronto", "Vancouver"]
t = np.linspace(start=0, stop=20, num=100)
data_df = pd.DataFrame({
"t": t,
cities[0]: np.sin(t),
cities[1]: np.cos(t),
cities[2]: np.sin(t + 2),
})
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
# HTML layout
app.layout = html.Div(children=[
dcc.Location(id="initialization", refresh=False),
html.Div(
[
html.Div([dcc.Dropdown(
id="city-dropdown",
placeholder="Select a city",
multi=False,
)], style={"width": "20%", "display": "inline-block"}),
html.Div([html.Button("Add a city", id="add-city-button", value="testing", style={"width": "20%", "display": "inline-block"})]),
],
),
html.Div(dcc.Graph(id="ts-plot"))
])
# Callbacks
@app.callback(
Output("city-dropdown", "options"),
[Input("initialization", "search")]
)
def available_cities(unused_string):
return [{"label": city, "value": city} for city in cities]
@app.callback(
Output("ts-plot", "figure"),
[
Input("city-dropdown", "value"),
Input("add-city-button", "n_clicks")
]
)
def update_figure(selected_city, n_clicks):
if selected_city is None:
data = []
else:
data = [go.Scatter(
x=data_df["t"],
y=data_df[selected_city],
mode="lines",
line={"dash": "dash"},
name="testing"
)]
return {
"data": data,
"layout": dict(
xaxis={"title": "time", "range": [data_df["t"].min(), data_df["t"].max()]},
yaxis={"title": "", "range": [-2, 2]},
hovermode="closest"
),
}
if __name__ == '__main__':
app.run_server(debug=True)
currrently, the dashboard looks like the following: