How to put two graphs side by side in Dash Python - 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.

Related

Display interactive metrics within dbc.Card - Dash

I'm aiming to include interactive counts as metrics. Specifically, insert total sums within cards that will changed depending on the variable selected from a nav bar.
Using below, the Navbar is used to display the proportion of successes and failures as a pie chart. I want to use the corresponding sums of success_count and failure_count as a metric to be displayed as a number.
Is it possible to return these values and display them within the designated dbc.Card?
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import plotly.express as px
import plotly.graph_objs as go
import dash
from dash import dcc
from dash import html
import dash_bootstrap_components as dbc
from dash.dependencies import Input, Output
# This dataframe has 244 lines, but 4 distinct values for `day`
url="https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBM-DS0321EN-SkillsNetwork/datasets/spacex_launch_dash.csv"
spacex_df = pd.read_csv(url)
spacex_df.rename(columns={'Launch Site':'Site'}, inplace=True)
external_stylesheets = [dbc.themes.SPACELAB, dbc.icons.BOOTSTRAP]
app = dash.Dash(__name__, external_stylesheets = external_stylesheets)
success_card = dbc.Card(
[
dbc.CardHeader("Some header"),
dbc.CardBody(
[
html.H6("Success Count", className="card-title"),
html.P("###total count of successes", className="card-text"),
]
),
],
className='text-center m-4'
)
failure_card = dbc.Card(
[
dbc.CardHeader("Some header"),
dbc.CardBody(
[
html.H6("Failure Count", className="card-title"),
html.P("##total count of failures", className="card-text"),
]
),
],
className='text-center m-4'
)
nav_bar = html.Div([
html.P("site-dropdown:"),
dcc.Dropdown(
id='Site',
value='Site',
options=[{'value': x, 'label': x}
for x in ['CCAFS LC-40', 'CCAFS SLC-40', 'KSC LC-39A', 'VAFB SLC-4E']],
clearable=False
),
])
app.layout = dbc.Container([
dbc.Row([
dbc.Col(html.Div(nav_bar, className="bg-secondary h-100"), width=2),
dbc.Col([
dbc.Row([
dbc.Col(success_card),
]),
dbc.Row([
dbc.Col(dcc.Graph(id = 'pie-chart'), style={
"padding-bottom": "10px",
},),
]),
dbc.Row([
# insert pie chart
dbc.Col(dcc.Graph(id = "bar-chart")),
]),
], width=5),
dbc.Col([
dbc.Row([
dbc.Col(failure_card),
]),
dbc.Row([
# insert bar chart
dbc.Col(dcc.Graph()),
], className="h-100"),
], width=5),
])
], fluid=True)
#app.callback(
Output("pie-chart", "figure"),
[Input("Site", "value")])
def generate_chart(value):
pie_data = spacex_df[spacex_df['Site'] == value]
success_count = sum(pie_data['class'] == 0)
failure_count = sum(pie_data['class'] == 1)
fig = go.Figure(data=[go.Pie(labels=['success','failure'], values=[success_count, failure_count])])
fig.update_layout(title=f"Site: {value}")
return fig
if __name__ == '__main__':
app.run_server(debug=True)
You should use html.Div in your card with id and then return html.P in this Div. Something as below:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import plotly.express as px
import plotly.graph_objs as go
import dash
from dash import dcc
from dash import html
import dash_bootstrap_components as dbc
from dash.dependencies import Input, Output
# This dataframe has 244 lines, but 4 distinct values for `day`
url="https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBM-DS0321EN-SkillsNetwork/datasets/spacex_launch_dash.csv"
spacex_df = pd.read_csv(url)
spacex_df.rename(columns={'Launch Site':'Site'}, inplace=True)
external_stylesheets = [dbc.themes.SPACELAB, dbc.icons.BOOTSTRAP]
app = dash.Dash(__name__, external_stylesheets = external_stylesheets)
success_card = dbc.Card(
[
dbc.CardHeader("Some header"),
dbc.CardBody(
[
html.H6("Success Count", className="card-title"),
html.Div(id='count_of_success'),
]
),
],
className='text-center m-4'
)
failure_card = dbc.Card(
[
dbc.CardHeader("Some header"),
dbc.CardBody(
[
html.H6("Failure Count", className="card-title"),
html.Div(id='count_of_failure'),
]
),
],
className='text-center m-4'
)
nav_bar = html.Div([
html.P("site-dropdown:"),
dcc.Dropdown(
id='Site',
value='Site',
options=[{'value': x, 'label': x}
for x in ['CCAFS LC-40', 'CCAFS SLC-40', 'KSC LC-39A', 'VAFB SLC-4E']],
clearable=False
),
])
app.layout = dbc.Container([
dbc.Row([
dbc.Col(html.Div(nav_bar, className="bg-secondary h-100"), width=2),
dbc.Col([
dbc.Row([
dbc.Col(success_card),
]),
dbc.Row([
dbc.Col(dcc.Graph(id = 'pie-chart'), style={
"padding-bottom": "10px",
},),
]),
dbc.Row([
# insert pie chart
dbc.Col(dcc.Graph(id = "bar-chart")),
]),
], width=5),
dbc.Col([
dbc.Row([
dbc.Col(failure_card),
]),
dbc.Row([
# insert bar chart
dbc.Col(dcc.Graph()),
], className="h-100"),
], width=5),
])
], fluid=True)
#app.callback(
[Output("pie-chart", "figure"),
Output("count_of_success", "children"),
Output("count_of_failure", "children")],
[Input("Site", "value")])
def generate_chart(value):
pie_data = spacex_df[spacex_df['Site'] == value]
success_count = sum(pie_data['class'] == 0)
failure_count = sum(pie_data['class'] == 1)
fig = go.Figure(data=[go.Pie(labels=['success','failure'], values=[success_count, failure_count])])
fig.update_layout(title=f"Site: {value}")
return fig, html.P(f'###total count of successes are: {success_count}'), html.P(f'###total count of failure are: {failure_count}')
if __name__ == '__main__':
app.run_server(debug=False)
And here is the result:

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"

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