Chage a different vol with Dash_Slicer - python

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)
`

Related

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)

Dash : Dynamically update an element based on radio option selected

I have a radio element and a text box element in my dash application. I'd like to update the text the field based on the selected option from a callback.
dbc.InputGroup(
[
dbc.RadioItems(
id="type",
persistence=True,
persistence_type="memory",
options=[
{"label": "option1", "value": "option1"},
{"label": "option2", "value": "option2"}
],
value="option1",
style={"margin-left":"8px"}
),
],
style={"margin-top":"20px","width": "80%", "float": "left"},
),
dbc.InputGroup(
[
dbc.InputGroupAddon("Floor", style={"margin-left":"8px"}),
dbc.Input(
id="floor",
persistence=True,
persistence_type="memory"
),
],
),
How do I make the text "Floor" to be dynamic based on the option selected in the radio?
You need to use the #app.callback in order to make your InputGroupAddon dynamic
import dash
from dash.dependencies import Input, Output
import dash_core_components as dcc
import dash_html_components as html
import dash_bootstrap_components as dbc
app = dash.Dash(__name__)
app.layout = (
html.Div([
dbc.InputGroup([
dbc.RadioItems(
id="type",
persistence=True,
persistence_type="memory",
options=[
{"label": "option1", "value": "option1"},
{"label": "option2", "value": "option2"}
],
value="option1",
style={"margin-left":"8px"}
),
],
style={"margin-top":"20px","width": "80%", "float": "left"},
),
dbc.InputGroup([
dbc.InputGroupAddon(
id='dbc-input-addon',
style={"margin-left":"8px"}),
dbc.Input(
id="floor",
persistence=True,
persistence_type="memory"
),
])
])
)
#app.callback(
Output(component_id='dbc-input-addon', component_property='children'),
[Input(component_id='type', component_property='value')]
)
def change_input(option_value):
if option_value == 'option1':
input_txt = 'Floor'
elif option_value == 'option2':
input_txt = 'No floor'
return input_txt
if __name__ == '__main__':
app.run_server(debug=True)

Plotly Dash Update Drop Down from call back where data frame inside the call back

I am trying to update the drop-down menu from the data frame column value where my data frame is generated inside call back since I am taking user inputs and extracting some data from API.
I want to create a filter in the dropdown that's why I want that drop-down updated dynamically using the data frame column.
so in a call back I have df['name_id'] through which I want to update the segment dropdown.
I have taken the only important line to break in my code since the code is too lengthy:
import dash_core_components as dcc
import dash_html_components as html
import dash_bootstrap_components as dbc
import datetime
import dash_table
import httplib2
import pandas as pd
import requests
import io
import time
from Dash_App.app import app
from dash.dependencies import Input, Output, State
from oauth2client import GOOGLE_REVOKE_URI, GOOGLE_TOKEN_URI, client
from oauth2client import client, GOOGLE_TOKEN_URI
from datetime import date, timedelta
from apiclient import discovery
row1 = html.Div(
[
dbc.Row([
dbc.Col([
dbc.Input(id="client_id",
type="text",
placeholder="Client ID",
style={'width': '150px'}, persistence=True,
persistence_type='memory'),
]),
], align="center"),
], style={'margin-top': 20, 'margin-left': -90}
)
row2 = html.Div([
dbc.Row([
dbc.Col([
dcc.Dropdown(
id='segment',
options=[{'label': i, 'value': i} for i in "what"],
multi=True,
style={'width': '250px'},
placeholder='Segment'),
]),
])
])
tab_2_layout = dbc.Container(children=[
row1,
html.Br(),
row2,
]
)
#app.callback(Output('output_div-ga', 'children'),
[Input('submit-button', 'n_clicks')],
[State('client_id', 'value'),
],
)
def ga_output(clicks, client_id):
if clicks is not None:
my_client_id = client_id
credentials = client.OAuth2Credentials(
access_token=None, # set access_token to None since we use a refresh token
client_id=my_client_id)
credentials.refresh(httplib2.Http()) # refresh the access token (optional)
http = credentials.authorize(httplib2.Http()) # apply the credentials
service_v3 = discovery.build('analytics', 'v3', http=http)
segments = service_v3.management().segments().list().execute()
df = pd.DataFrame(segments['items'])
df = df[['name', 'id']]
df['name_id'] = df.name.astype(str).str.cat(df.id.astype(str), sep=':')
return html.Div([dcc.Store('memory'),
dash_table.DataTable(
id='table',
columns=[{"name": i, "id": i} for i in dff.columns],
data=dff.to_dict("rows"), persistence=True, persistence_type='memory',
export_format="csv",
),
])
I am able to solve this by generating form inside call back.
return html.Div([
dbc.Row([
dbc.Col([
dcc.Dropdown(
id='segment',
options=[{'label': i, 'value': i} for i in df['name_id'].unique()],
persistence=True, persistence_type='memory',
multi=True,
style={'width': '250px', 'margin-left': -250, 'margin-top': 10},
placeholder='Segment'),
]), ]), ])
What worked for me was to give each column that you want to edit an id, make it editable and then update the dropdown options in the DataTable. I also returned the whole DataTable in my callback.
app.callback(
Output("table-dropdown-container", "children"),
Input("input-data-table-id", "data"),
)(self.update_unlabelled_shops_table)
...
dt = (
dash_table.DataTable(
id='table-id',
data=df.to_dict("records"),
columns=[{"name": i, "id": i} if i != column_name else {"name": i, "id": i, "editable": True, "presentation": "dropdown"} for i in df.columns],
page_size=8,
dropdown={
column_name: {
"options": [
{"label": i, "value": i}
for i in df[column_name].unique()
]
},
},
),
)
return dt
except Exception as e:
print(e)
return [None]
And to create your div block.
def create_div(self):
return html.Div(
[
dash_table.DataTable(
id='table-id',
columns=[],
editable=True,
dropdown={},
),
html.Div(id="table-dropdown-container"),
]
)
Hope this helps somebody...

Dash range slider with input on each side

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)

save a modified dash datatable to dataframe

I'm new to dash and I'm struggling to save the edits made on the dash data table back to a data frame
here is my code of the data table
import dash
from dash.dependencies import Input, Output, State
import dash_table
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd
import sqlalchemy
app = dash.Dash(__name__)
engine = sqlalchemy.create_engine('mysql+pymysql://root:#127.0.0.1:3306/sfp')
df = pd.read_sql_table("base_case",engine)
app.layout = html.Div([
html.Div([
dcc.Input(
id='adding-rows-name',
placeholder='Enter a column name...',
value='',
style={'padding': 10}
),
html.Button('Add Column', id='adding-rows-button', n_clicks=0)
], style={'height': 50}),
dash_table.DataTable(
id='adding-rows-table',
columns=[{"name": i, "id": i} for i in df.columns],
data=df.to_dict('records'),
editable=True,
row_deletable=True
),
html.Button('Add Row', id='editing-rows-button', n_clicks=0),
])
if __name__ == '__main__':
app.run_server(debug=True)
is there any solution to do that ?
You need a callback for it and this is an example how you could do it:
import dash
import dash_table
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd
app = dash.Dash(__name__)
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/solar.csv')
nmb_clicks = 0
app.layout = html.Div([
dcc.Store(id='click-memory', data = {'nmb_clicks': nmb_clicks}),
html.Div([
dcc.Input(
id='adding-rows-name',
placeholder='Enter a column name...',
value='',
style={'padding': 10}
),
html.Button('Add Column', id='adding-columns-button', n_clicks=nmb_clicks)
], style={'height': 50}),
dash_table.DataTable(
id='adding-rows-table',
columns=[{"name": i, "id": i} for i in df.columns],
data=df.to_dict('records'),
editable=True,
row_deletable=True
),
html.Button('Add Row', id='editing-rows-button', n_clicks=0),
])
#app.callback(dash.dependencies.Output('adding-rows-table', 'columns'),
[dash.dependencies.Input('adding-columns-button', 'n_clicks'),
dash.dependencies.Input('adding-rows-name', 'value')],
[dash.dependencies.State('click-memory', 'data')])
def update_dropdown(click, name, data):
if click != data['nmb_clicks']:
if name not in df.columns:
df[name] = [float('nan')] * len(df.index)
return [{"name": i, "id": i} for i in df.columns]
#app.callback(dash.dependencies.Output('click-memory', 'data'),
[dash.dependencies.Input('adding-columns-button', 'n_clicks')],
[dash.dependencies.State('click-memory', 'data')])
def on_data(click, data):
if click != nmb_clicks:
data['nmb_clicks'] = data['nmb_clicks'] + 1
return data
if __name__ == '__main__':
app.run_server(debug=True)
Note that you would need to fill the column with some meaningful values (now empty cell are being inserted).

Categories