FS2023-dashboard-design/dashboard2/main.py

76 lines
2.3 KiB
Python
Raw Normal View History

import math
from dash import Dash, dcc, html, Input, Output
import plotly.express as px
import numpy as np
import pandas as pd
import dash_bootstrap_components as dbc
app = Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP])
# generate random normal distributed data for x and y
# and store it in a pandas DataFrame
df = pd.DataFrame({'y': np.random.normal(loc=0, scale=10, size=1000),
'x': np.random.normal(loc=10, scale=2, size=1000)})
2023-05-12 15:12:05 +02:00
df_min = math.floor(df["y"].min())
df_max = math.ceil(df["y"].max())
2023-05-12 15:02:17 +02:00
app.layout = html.Div(
[
html.H1("Dashboard 2"),
dbc.Row(
[
dbc.Col(
[
dcc.Dropdown(
options=["red", "green", "blue"],
value="red",
id="color",
multi=False,
)
],
width=6,
),
dbc.Col(
[
dcc.RangeSlider(
2023-05-12 15:12:05 +02:00
min=df_min,
max=df_max,
value=[df_min, df_max],
2023-05-12 15:02:17 +02:00
id="range",
)
],
width=6,
),
]
),
dbc.Row(
[
dbc.Col([dcc.Graph(id="graph_1")], width=6),
dbc.Col([dcc.Graph(id="graph_2")], width=6),
]
),
],
className="m-4",
)
2023-05-12 15:48:53 +02:00
# Now the color selecion and the slider works for both diagrams
2023-05-12 15:23:37 +02:00
@app.callback(Output("graph_1", "figure"), Input("color", "value"), Input("range", "value"))
2023-05-12 15:23:37 +02:00
def update_graph_1(color, range):
2023-05-12 15:48:53 +02:00
# this filter is used twice. This could be improved
2023-05-12 15:23:37 +02:00
dff = df[(df['y'] > range[0]) & (df['y'] < range[1])]
fig = px.histogram(dff, x="y", color_discrete_sequence=[color])
fig.update_layout()
return fig
2023-05-12 15:23:37 +02:00
@app.callback(Output("graph_2", "figure"), Input("color", "value"), Input("range", "value"))
2023-05-12 15:23:37 +02:00
def update_graph_2(color, range):
2023-05-12 15:02:17 +02:00
dff = df[(df['y'] > range[0]) & (df['y'] < range[1])]
2023-05-12 15:23:37 +02:00
fig = px.scatter(dff, x='x', y='y', color_discrete_sequence=[color])
fig.update_layout()
return fig
if __name__ == '__main__':
app.run_server(debug=True, port=8000)