Dash range slider with input on each side - python

I am quite new to front-end development and HTML and I'm struggling to understand how to order a range slider with two inputs in the same line when using Dash
I have tried to separate the html.Div, Putting the components in the same Div without separating them
adjust the different parameters and some morebut I still can't get it to appear the way I want
what I want:
what I have:
My code (that reproduce what I have):
import dash
import dash_core_components as dcc
import dash_html_components as html
app.layout = html.Div([
html.Div([
html.Div([dcc.Input(
id='slider-min-value',
placeholder=str(min_value))],
style={'width': '10%'}
),
html.Div([dcc.RangeSlider(
id='condition-range-slider',
min=0,
max=30,
value=[10, 15],
allowCross=False)],
style={'width': '25%'}
),
html.Div([dcc.Input(
id='slider-max-value',
placeholder=str(max_value))],
style={'width': '10%'}
),
],
style={'display': 'inline-block'})])
if __name__ == '__main__':
app.run_server(debug=True)
what do I need to do in order to get the rangeslider and the inputs to appear the way I want?

Ok, using {"display": "grid", "grid-template-columns": "10% 40% 10%"} gave me what I wanted.
layout:
app.layout = html.Div(
html.Div(
[
dcc.Input(type='text', value=min_value),
dcc.RangeSlider(
id='condition-range-slider',
min=0,
max=30,
value=[10, 15],
allowCross=False
),
dcc.Input(type='text', value=max_value)
],
style={"display": "grid", "grid-template-columns": "10% 40% 10%"}),
style={'width': '20%'}
)
what I got:

You can try updating the html.Div style with 'float': 'left',
import dash
import dash_core_components as dcc
import dash_html_components as html
app = dash.Dash(__name__)
app.layout = html.Div(
[
html.Div(
style={'width':'10%', 'float':'left', 'marginLeft': 20, 'marginRight': 20},
children=[
dcc.Input(id='slider-min-value')
]
),
html.Div(
style={'width':'50%', 'float':'left','marginLeft': 20, 'marginRight': 20},
children=[
dcc.RangeSlider(
id='condition-range-slider',
min=0,
max=30,
value=[10, 15],
allowCross=False
)
]
),
html.Div(
style={'width':'10%', 'float':'left','marginLeft': 20, 'marginRight': 20},
children=[
dcc.Input(id='slider-max-value')
]
),
])
if __name__ == '__main__':
app.run_server(debug=True)

Related

How to have a customized CSS style for a bootstrap component?

I have the code below that has a bootstrap offcanvas at the left. I wondered how I can change the width of the collapsed sidebar. Bootstrap does not have a style tag to do that. I searched and I saw some people suggested using a customized CSS style to define new styling. Can you please help me with that I am pretty new to styling, and I don’t know where I should start.
from dash import Dash, html, dcc, Input, Output, State
import dash_bootstrap_components as dbc
from dash_iconify import DashIconify
app = Dash(__name__, use_pages=True, external_stylesheets=[dbc.themes.SPACELAB])
sidebar = dbc.Nav([
dbc.NavLink([
html.Div(page["name"], className="ms-2"),
], href=page["path"],
active="exact",
)
for page in dash.page_registry.values()
], vertical=True,
pills=True,
className="bg-light",
)
download_icon = DashIconify(icon='ic:baseline-menu', width=40, style={})
app.layout = dbc.Container([
dbc.Row([
dbc.Col(
html.Div("Drilling Dashboard",
style={'fontSize': 40,
'textAlign': 'center',
'color': 'white'}
)
),
dbc.Col([
dbc.Button([download_icon, ''], id="open-offcanvas", n_clicks=0),
], width=1,
style={'margin-right': 0,
'padding': 5}
),
]),
html.Hr(
style={'margin-top': 0}
),
dbc.Row([
dbc.Offcanvas(
dbc.Col([sidebar], width=5), id="offcanvas", title="Title", is_open=False, style={'horizontal-width': 10}
),
]),
dbc.Row([
dbc.Col([dash.page_container], xs=8, sm=8, md=10, lg=10, xl=10, xxl=10)
])
], fluid=True,
style={'background-color': 'black'})
#app.callback(
Output("offcanvas", "is_open"),
Input("open-offcanvas", "n_clicks"),
[State("offcanvas", "is_open")],
)
def toggle_offcanvas(n1, is_open):
if n1:
return not is_open
return is_open
if __name__ == "__main__":
app.run(debug=True)
You can change the width of sidebar by the following attribute:
dbc.Offcanvas(
dbc.Col([sidebar], width=8),
id="offcanvas",
title="Title",
is_open=False,
style={'width': 100} #<---- this attribute instead of horizental-width
)
Output

How to put two graphs side by side in Dash Python

I'm trying to put these two graphs side by side in dash, I already used inline block but it's still not working, could anyone help me here?
app = dash.Dash(__name__)
app.layout = html.Div([
html.Div([
html.H1('Vacunados por covid'),
#html.Img(src='assets/vacuna.png')
], className = 'banner'),
html.Div([
html.Div([
html.P('Selecciona la dosis', className = 'fix_label', style={'color':'black', 'margin-top': '2px'}),
dcc.RadioItems(id = 'dosis-radioitems',
labelStyle = {'display': 'inline-block'},
options = [
{'label' : 'Primera dosis', 'value' : 'primera_dosis_cantidad'},
{'label' : 'Segunda dosis', 'value' : 'segunda_dosis_cantidad'}
], value = 'primera_dosis_cantidad',
style = {'text-aling':'center', 'color':'black'}, className = 'dcc_compon'),
], className = 'create_container2 five columns', style = {'margin-bottom': '20px'}),
], className = 'row flex-display'),
html.Div([
html.Div([
dcc.Graph(id = 'my_graph', figure = {}),
], className = 'create_container2 eight columns', style={'display': 'inline-block'}),
html.Div([
dcc.Graph(id = 'pie_graph', figure = {})
], className = 'create_container2 five columns')
], className = 'row flex-display', style={'display': 'inline-block'}),
], id='mainContainer', style={'display':'flex', 'flex-direction':'column'})
Please refer this below code for your case:
import pandas as pd
import numpy as np
import plotly.express as px
import dash
import dash_html_components as html
import dash_core_components as dcc
from dash.dependencies import Input, Output
import dash_bootstrap_components as dbc
import plotly.graph_objects as go
app = dash.Dash(__name__)
app.layout = html.Div([
html.Div([
html.H1('Vacunados por covid'),
#html.Img(src='assets/vacuna.png')
], className = 'banner'),
html.Div([
html.Div([
html.P('Selecciona la dosis', className = 'fix_label', style={'color':'black', 'margin-top': '2px'}),
dcc.RadioItems(id = 'dosis-radioitems',
labelStyle = {'display': 'inline-block'},
options = [
{'label' : 'Primera dosis', 'value' : 'primera_dosis_cantidad'},
{'label' : 'Segunda dosis', 'value' : 'segunda_dosis_cantidad'}
], value = 'primera_dosis_cantidad',
style = {'text-aling':'center', 'color':'black'}, className = 'dcc_compon'),
], className = 'create_container2 five columns', style = {'margin-bottom': '20px'}),
], className = 'row flex-display'),
html.Div([
html.Div([
dcc.Graph(id = 'my_graph', figure = {}),
], style={'width': '69%','display': 'inline-block'}),
html.Div([
dcc.Graph(id = 'pie_graph', figure = {})
], style={'width': '29%', 'display': 'inline-block'})
], className="row"),
], id='mainContainer', style={'display':'flex', 'flex-direction':'column'})
if __name__ == "__main__":
app.run_server(debug=False)
Or you can learn about dash bootstrap component with Row and Column.

Chage a different vol with Dash_Slicer

I’m trying to change automatically the vol when someone choose the option from the dropdown, I have eje2.npz, eje3.npz, eje4.npz. This in order to have a different database and show different images with dashslider.
The dash_slider doesnt have an id as other ddc.
I am out of ideas.
import dash
import dash_html_components as html
import imageio
import dash_bootstrap_components as dbc
from dash_slicer import VolumeSlicer
from dash import Dash, dcc, html, Input, Output
app = dash.Dash(__name__, update_title=None)
vol = imageio.volread("eje1.npz")
slicer = VolumeSlicer(app, vol)
slicer.graph.config["scrollZoom"] = False
app.layout = dbc.Container([
dbc.Row([
html.H1("Reporte sobre postura", style={'text-align': 'center'}),
]),
dbc.Row([
dbc.Col([
dcc.Dropdown(id="slct_30",
options=[
{"label": "PRIMER", "value": 1},
{"label": "SEGUNDO", "value": 2},
{"label": "TERCERO", "value": 3},
{"label": "CUARTO", "value": 4}],
multi=False,
value=1,
style={'width': "80%"}
),
html.Div(id='output_container', children=[]),
html.Br(),
],width={'size':5, 'offset':5},),
]),
dbc.Row([
slicer.graph, slicer.slider, *slicer.stores
]),
])
#app.callback(
[Output(component_id='output_container',component_property='children')],
[Output(component_id='post_%', component_property='figure')],
[Input(component_id='slct_30', component_property='value')]
)
def update_graph(option_slctd):
print(option_slctd)
print(type(option_slctd))
container = "LAPSO DE 30 MINUTOS: {}".format(option_slctd)
return container
if __name__ == "__main__":
app.run_server(debug=True, dev_tools_props_check=False)
`

Sidebar with filters (dropdowns) in Plotly Dash

I am trying to program a sidebar with some filters but the callback update_output of this dropdown is not working (not throwing an error, just doing nothing).
I think it is because this dropdown is not in the main layout, because my layout is composed of the sidebar and a content. My dropdowns in this sidebar will be filters that will be applied to the dataframe that feeds the graphs of the dashboard and dashboard2 layouts.
My question is how or where should I program those callbacks to give functionality to my sidebar dropdowns?
sidebar = html.Div(
[
html.H2("Sidebar", className="display-4"),
html.Hr(),
html.P(
"Sidebar", className="lead"
),
dbc.Nav(
[
dbc.NavLink("Home", href="/", active="exact"),
dbc.NavLink("Page 1", href="/page-1", active="exact"),
dbc.NavLink("Page 2", href="/page-2", active="exact"),
],
vertical=True,
pills=True,
),
dcc.Dropdown(id='dropdown',value="City"),
html.Br(),
dcc.Dropdown(id='dropdown2',options=[])
],
style=SIDEBAR_STYLE,
)
content = html.Div(id="page-content", children=[], style=CONTENT_STYLE)
app.layout = html.Div([
dcc.Location(id="url"),
sidebar,
content
])
#app.callback(
Output('dropdown2', 'options'),
Input('dropdown', 'value')
)
def update_output(value):
return df[df["cities"].isin(value)]
#app.callback(
Output("page-content", "children"),
[Input("url", "pathname")]
)
def render_page_content(pathname):
if pathname == "/":
return dashboard.layout
elif pathname == "/page-1":
return dashboard.layout
elif pathname == "/page-2":
return dashboard2.layout
# return a 404 message when user tries to reach a different page
return dbc.Jumbotron(
[
html.H1("404: Not found", className="text-danger"),
html.Hr(),
html.P(f"The pathname {pathname} was not recognised..."),
]
)
if __name__=='__main__':
app.run_server(debug=True, port=8000)
I find checklists to be better for this purpose. If you're open to using that instead of dropdown menu to filter your dataframe, then the complete snippet below will produce the following Plotly Dash App.
Complete code:
from jupyter_dash import JupyterDash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State, ClientsideFunction
import dash_bootstrap_components as dbc
import dash_core_components as dcc
import pandas as pd
import plotly.graph_objs as go
import numpy as np
import plotly.express as px
app = JupyterDash(external_stylesheets=[dbc.themes.SLATE])
df = px.data.stocks()
df = df.set_index('date')
controls = dbc.Card(
[
dbc.FormGroup(
[
dbc.Label("Checklist"),
dcc.Checklist(
id="column_select",
options=[{"label":col, "value": col} for col in df.columns],
value=[df.columns[0]],
labelStyle={'display': 'inline-block', 'width': '12em', 'line-height':'0.5em'}
),
],
),
],
body=True,
style = {'font-size': 'large'}
)
app.layout = dbc.Container(
[
html.H1("Dropdowns and checklists"),
html.Hr(),
dbc.Row([
dbc.Col([controls],xs = 4),
dbc.Col([
dbc.Row([
dbc.Col(dcc.Graph(id="graph"), style={'height': '420px'}),
])
]),
]),
],
fluid=True,
)
#app.callback(
Output("graph", "figure"),
[Input("column_select", "value"),],
)
def make_graph(cols):
fig = px.line(df, x = df.index, y = cols, template = 'plotly_dark')
return fig
app.run_server(mode='external', port = 8982)

Update values of a table by clicking on different parameters in the drop-down menu. Dash Python

Can someone help me to detect why when selecting the branchpoint parameter from the drop-down menu, the table value is not updated?
I understand that the drop-down menu options work as a button and pressing it should update the table values.
Thank you.
The code with jupyter notebook is the following one.
from dash.exceptions import PreventUpdate
from dash.dependencies import Input, Output
import dash_table
import dash_core_components as dcc
import dash_html_components as html
import dash
from jupyter_dash import JupyterDash
from dash.dependencies import Input, Output, State
import dash_bootstrap_components as dbc
from dash_table import DataTable, FormatTemplate
import cv2
import numpy as np
from mahotas.morph import hitmiss as hit_or_miss
app = JupyterDash(__name__)
server = app.server
percentage = FormatTemplate.percentage(2)
biomarkers = dbc.Card(
id = 'biomarkers',
children = [
dbc.CardHeader(html.H5(dbc.Badge("Ratios of biomarkers",className="m1-1"))),
dbc.CardBody(html.Div([
'Choose biomarker to calculate the ratio: ',
dcc.Dropdown(
id='biomarkers-options',
options=[
{'label': prop, 'value': prop}
for prop in [
'branchpoints', 'endpoints', 'mediumlength',
'totallength', 'specularoverlap']
]
),
html.Br(),
dash_table.DataTable(
columns = [
dict(id='parameter', name='Parameter'),
dict(id='rate', name='Rate', type='numeric', format=percentage)
],
data = [
dict(parameter='Branch Points', rate=0),
dict(parameter='End Points', rate=0),
dict(parameter='Medium Length', rate=0),
dict(parameter='Total Length', rate=0),
dict(parameter='Specular Overlap', rate=0)
],
editable=True
)
]),
),
],
# style={"width": "18rem"},
),
app.layout = html.Div(
[
dbc.Container(
children=[
dbc.Row([dbc.Col(biomarkers, md=4)]),
],
fluid= True,
),
]
)
#app.callback(
Output('loading-table', 'data'),
Input('biomarkers-options', 'value'),
State("loading-table", "data")
)
def loading_bp(value, table):
if value == 'branchpoints':
calcperbranchhem1=(50/(20+40))
else:
calcperbranchhem1=(50/(20+40))
return html.Div([
dash_table.DataTable(
id='loading-table',
columns = [
dict(id='parameter', name='Parameter'),
dict(id='rate', name='Rate', type='numeric', format=percentage)
],
data = [
dict(parameter='Branch Points', rate=calcperbranchhem1),
dict(parameter='End Points', rate=0),
dict(parameter='Medium Length', rate=0),
dict(parameter='Total Length', rate=0),
dict(parameter='Specular Overlap', rate=0)
],
editable=True
)
])
if __name__ == '__main__':
# Run app and display result inline in the notebook
app.run_server(mode='inline', host="localhost",port=8053)
You have
State("loading-table", "data")
but no "loading-table"

Categories