Align dash core components horizontally - python

I want to align two Dropdown menus and a DatePickerRange horizontally. But with the following code:
import dash
import dash_core_components as dcc
import dash_html_components as html
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
style_dict = dict(width='100%',
border='1.5px black solid',
height='50px',
textAlign='center',
fontSize=25)
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
app.layout = html.Div(children=[
html.H1(children='Hello Dash'),
# placeholder
html.Div(style={'width': '2%', 'display': 'inline-block'}),
html.Div(
dcc.Dropdown(
id = 'start_hour',
options = [{'label': i, 'value': i} for i in list(range(0,24))],
style=style_dict,
), style={'width': '20%', 'display': 'inline-block'}),
# placeholder
html.Div(style={'width': '2%', 'display': 'inline-block'}),
html.Div(
dcc.DatePickerRange(
id='date_picker_range',
style=style_dict
), style={'width': '14%', 'display': 'inline-block', 'fontSize': 20}),
# placeholder
html.Div(style={'width': '2%', 'display': 'inline-block'}),
html.Div(
dcc.Dropdown(
id = 'end_hour',
options = [{'label': i, 'value': i} for i in list(range(0,24))],
style=style_dict
), style={'width': '20%', 'display': 'inline-block'}),
])
if __name__ == '__main__':
app.run_server(debug=False, use_reloader=False)
I got this layout:
If I zoom in I got this:
Is it possible to force the components to be aligned at the top edge, no matter how I zoom in or out?
As browser I use Firefox.

I had a problem similar to the one you are describing. I was creating a dashboard that looked like this:
dcc components without proper alignement
As you can see in the image, my dcc components, as well as their titles were not aligned correctly. I tried adding the style parameter verticalAlign and it worked as I expected. This is how the dashboard looked after adding that style parameter:
dcc components aligned
I'm attaching my dashboard Layout code so you can see where I placed the parameter mentioned:
## Dashboard layout
app.layout = html.Div( ## Master div
[
html.Div( ## Dashboard title
[
dcc.Markdown(dash_title)
]
),
html.Div( ## Select menus
[
html.Div( ## Stock select
[
dcc.Markdown(dash_stock_sel),
dcc.Dropdown(
id="select_stock",
options=[{"label": cmp, "value": tickers_base[cmp]["symbol"]} for cmp in tickers_base],
value="TSLA"
)
],
style={
"display": "inline-block",
"width": "20%"
}
),
html.Div( ## Date select dcc components
[
dcc.Markdown(dash_date_sel),
dcc.DatePickerRange(
id="select_dates",
min_date_allowed=date(2015, 1, 1),
max_date_allowed=date.today(),
initial_visible_month=date(2015, 1, 1),
end_date=date.today()
)
],
style={
"display": "inline-block",
"width": "30%",
"margin-left": "20px",
"verticalAlign": "top"
}
),
]
),
html.Div( ## Stock prices graph
[
dcc.Graph(
id="cstock_graph",
figure=stock_graph(def_company, datareader_api, def_start, def_end)
)
]
)
]
)
I hope this answer helps!

Related

How to update rows in data table when changing radio items

Ok, so the thing is that everytime I change from page with the radio item button, I want the table of this to change to another one, but I'm not sure how this can be done, so here is the code if someone could help me.
app = dash.Dash(__name__)
app.layout = html.Div([
html.Div([
html.H1('Viviendas disponibles'),
#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' : 'Registro', 'value' : 'primera_dosis_cantidad'},
{'label' : 'Verificacion', 'value' : 'segunda_dosis_cantidad'},
{'label' : 'Produccion', 'value' : 'tercera_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': '49%','display': 'inline-block'}),
html.Div([
dcc.Graph(id = 'pie_graph2', figure = {}),
], style={'width': '50%','display': 'inline-block'}),
], className="row"),
html.Div([
dash_table.DataTable(df.iloc[[-1]].to_dict('records'), [{"name": i, "id": i} for i in df.columns[2:10]]),
html.Br()]),
html.Div([
html.Div([
dcc.Graph(id = 'pie_graph4', figure = {}),
], style={'width': '49%','display': 'inline-block'}),
html.Div([
dcc.Graph(id = 'pie_graph3', figure = {})
], style={'width': '49%', 'display': 'inline-block'})], className="row"),
html.Div([
dash_table.DataTable(df.iloc[[-1]].to_dict('records'), [{"name": i, "id": i} for i in df.columns[12:16]])
]),
], id='mainContainer', style={'display':'flex', 'flex-direction':'column'})
So as you can see, the main table I would like to change is the one that says: dash_table.DataTable(df.iloc[[-1]].to_dict('records'), [{"name": i, "id": i} for i in df.columns[2:10]])
So, anyone has idea on how to do this?

Additional elements inline with Dash's dcc.Tabs?

For my Dash app, I want to create a navigation bar that has links to the different pages but also additional stuff, e.g. the currently logged in user, and logos and stuff.
However, I unfortunately cannot use pages (Like in the "Navbar" example in dbc) since the WebApp has to be hosted as a single-url app inside another tool. My only option is to got with dcc.Tabs.
However, it looks to me like dcc.Tabs forces a newline behind the Tabs. I tried different things to prevent that, but nothing seems to be working. The best I got so far is the example below. How do I make it so that the text is in the same row as the Tabs element?
tabs_styles = {
'height': '44px', "width": "49%", "display":"inline-block"
}
app.layout = html.Div(children=[
html.Div(children=[
dcc.Tabs(id="tabs-styled-with-inline", value='tab-1', children=[
dcc.Tab(label='Page1', value='tab-1', style=tab_style, selected_style=tab_selected_style),
dcc.Tab(label='Page2', value='tab-2', style=tab_style, selected_style=tab_selected_style),
], style=tabs_styles)]),
html.Span(children=[
" Logged in as ",
html.Strong(id="username")
], style = tabs_styles),
html.Div(children=[
# Distance to header:
html.Hr(),
html.Div(id='tabs-content-inline')
])
])
Your inline style should be applied to the parent div of your Tabs component. I made some small modifications here (look at tabs_container_styles):
tabs_styles = {"height": "44px"}
tabs_container_styles = {"width": "49%", "display": "inline-block"}
app.layout = html.Div(
children=[
html.Div(
children=[
dcc.Tabs(
id="tabs-styled-with-inline",
value="tab-1",
children=[
dcc.Tab(label="Page1", value="tab-1"),
dcc.Tab(label="Page2", value="tab-2"),
],
style=tabs_styles,
)
],
style=tabs_container_styles,
),
html.Span(
children=[" Logged in as ", html.Strong(id="username")], style=tabs_styles
),
html.Div(
children=[
# Distance to header:
html.Hr(),
html.Div(id="tabs-content-inline"),
]
),
]
)
Set the parent_style property of your Tabs component instead of the style property and move your Span component to be a child of the div containing your Tabs component.
parent_style (dict; optional): Appends (inline) styles to the top-level parent container holding both the Tabs container and the content container.
style (dict; optional): Appends (inline) styles to the Tabs container holding the individual Tab components.
https://dash.plotly.com/dash-core-components/tabs
MRE
from dash import Dash, html, dcc
tabs_styles = {"height": "44px", "width": "49%", "display": "inline-block"}
app = Dash()
app.layout = html.Div(
children=[
html.Div(
children=[
dcc.Tabs(
id="tabs-styled-with-inline",
value="tab-1",
children=[
dcc.Tab(
label="Page1", value="tab-1", style={}, selected_style={}
),
dcc.Tab(
label="Page2", value="tab-2", style={}, selected_style={}
),
],
parent_style=tabs_styles,
),
html.Span(
children=[" Logged in as ", html.Strong(id="username")], style=tabs_styles
),
]
),
html.Div(
children=[
# Distance to header:
html.Hr(),
html.Div(id="tabs-content-inline"),
]
),
]
)
if __name__ == "__main__":
app.run_server()

How to insert several dropdowns in plotly dash

I am trying to get into using Plotly Dash and I am getting stuck on this one piece where I would like to dynamically add a user-defined number of dropdowns. Here is what I tried:
# Import required libraries
import dash
import math
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State
# App Begins
app = dash.Dash(
__name__, meta_tags=[{"name": "viewport", "content": "width=device-width"}],
)
app.title = "Tool"
server = app.server
# Create global chart template
mapbox_access_token = "pk.eyJ1IjoicGxvdGx5bWFwYm94IiwiYSI6ImNrOWJqb2F4djBnMjEzbG50amg0dnJieG4ifQ.Zme1-Uzoi75IaFbieBDl3A"
layout = dict(
autosize=True,
automargin=True,
margin=dict(l=30, r=30, b=20, t=40),
hovermode="closest",
plot_bgcolor="#F9F9F9",
paper_bgcolor="#F9F9F9",
legend=dict(font=dict(size=10), orientation="h"),
title="Satellite Overview",
mapbox=dict(
accesstoken=mapbox_access_token,
style="light",
center=dict(lon=-78.05, lat=42.54),
zoom=7,
),
)
# Create app layout
app.layout = html.Div(
[
dcc.Store(id="aggregate_data"),
# empty Div to trigger javascript file for graph resizing
html.Div(id="output-clientside"),
html.Div(
[
html.Div(
[
html.Img(
src=app.get_asset_url("dash-logo.png"),
id="plotly-image",
style={
"height": "60px",
"width": "auto",
"margin-bottom": "25px",
},
)
],
className="one-third column",
),
html.Div(
[
html.Div(
[
html.H3(
"Dash Tool",
style={"margin-bottom": "0px"},
),
]
)
],
className="one-half column",
id="title",
),
],
id="header",
className="row flex-display",
style={"margin-bottom": "25px"},
),
html.Div(
[
html.Div(
[
html.P("Quantity 1:", className="control_label"),
dcc.Input(
id="quantity_1",
type="number",
placeholder=33.
),
html.P("Quantity 2:", className="control_label"),
dcc.Input(
id="quantity_2",
type="number",
placeholder=-115.
),
html.P("Number of Drop Downs:", className="control_label"),
dcc.Slider(
id="drop_downs",
min=2,
max=10,
value=2,
step=1.0,
className="dcc_control",
),
html.P("Load Inputs:", className="control_label"),
dcc.Checklist(
id='sources_flag',
options=[
{'label': 'Yes', 'value': 'Y'},
],
value=['Y'],
labelStyle={'display': 'inline-block'}
),
html.Div(id='source_dropdown_container', children=[]),
html.Div(id='source_dropdown_container_output'),
html.Div(id='source_file_container', children=[]),
html.Div(id='source_file_container_output'),
],
className="pretty_container four columns",
id="cross-filter-options",
),
],
className="row flex-display",
),
],
id="mainContainer",
style={"display": "flex", "flex-direction": "column"},
)
# Create callbacks
#app.callback(
[
Output(component_id='source_dropdown_container_output', component_property='children'),
],
[
Input(component_id='drop_downs', component_property='value'),
Input(component_id='sources_flag', component_property='value'),
]
)
def update_source_dropdowns(value, value_1):
"""Controls the number of drop-downs available to choose sources"""
if value_1 == 'Y':
children = []
for i in range(0, value):
new_dropdown = dcc.Dropdown(
id=f'''source_dropdown_{str(i)}''',
options=['GOOG', 'FB', 'TDOC', 'FANG']
)
children.append(new_dropdown)
print(children)
print(type(children))
return children
I keep running into a callback error. The drop down is constructed properly, so I am kind of confused as to why that error is being invoked.
dash.exceptions.InvalidCallbackReturnValue: The callback ..source_dropdown_container_output.children.. is a multi-output.
Expected the output type to be a list or tuple but got:
None.
Any guidance or help is appreciated. All I am trying to do is add based on user input a dynamic number of drop downs to the layout.
you have three errors in your callback
there is only one return, hence do not define Output as a list
conditional check is wrong, should be if value_1 == ['Y']:
doc.Dropdown() options argument needs to define list of dict
# Create callbacks
#app.callback(
Output(component_id='source_dropdown_container_output', component_property='children'),
[
Input(component_id='drop_downs', component_property='value'),
Input(component_id='sources_flag', component_property='value'),
]
)
def update_source_dropdowns(value, value_1):
"""Controls the number of drop-downs available to choose sources"""
print("cb", value, value_1)
if value_1 == ['Y']:
children = []
for i in range(0, value):
new_dropdown = dcc.Dropdown(
id=f'''source_dropdown_{str(i)}''',
options=[{"label":v, "value":v } for v in ['GOOG', 'FB', 'TDOC', 'FANG']],
)
children.append(new_dropdown)
print(children)
print(type(children))
return children

Plotly Dash - Bootstrap's cards don't change of color [duplicate]

I'm trying to organize my Plotly Dash dashboard into sections of columns, but I can't understand what I'm doing wrong here. I've included my components in separate dbc.Cols within one dbc.Row and specified the width of the column I'd like for them to take up, but everything is just stacked. Ideally, I'd have the cards in a column all by themselves on the left, then I would have the questions next to them on the right. Can someone please help me diagnose what I'm doing that's causing all my components to stack?
#Import packages
import dash
import dash_core_components as dcc
import dash_bootstrap_components as dbc
import dash_html_components as html
from dash.dependencies import Input, Output, State
app = dash.Dash()
#App Layout
app.layout = html.Div([
dbc.Row(children=[
dbc.Col(id="card_col",width = 6),
dbc.Col(id="form", width=6, children=[
html.Div([
dbc.FormGroup(children=[
dbc.Label("Question 1"),
dbc.Col(
dcc.Input(type="text", id="q1", placeholder="Enter your info"),
width=6
)
],row=True)
]),
html.Br(),
html.Div(children=[
dbc.FormGroup(children=[
dbc.Label("Question 2?"),
dbc.Col(
dbc.Input(type="text",id="q2",placeholder="Enter your info"),
width=6
)
],row=True)
]),
html.Br(),
html.Div([
dbc.FormGroup(children=[
dbc.Label("Yes/No?"),
dbc.Col(
dbc.RadioItems(id="q3",options=[{"label": "Yes", "value": 1},
{"label": "No", "value": 2}
]
),width=6
)
],row=True)
]),
html.Br(),
html.Div([
html.Button(id='submit-button',
n_clicks=0,
children='Submit Query',
style={'fontSize':24})
])
]) #End of second column
]), #End of row,
dbc.Row(
html.Div([
dcc.Graph(id='graph1')
])
)
])
#app.callback(
Output('card_col','children'),
Input('submit-button','n_clicks'),
State('q1','value'),
State('q2','value'),
State('q3','value'))
def update_cards(n_clicks,input1,input2,input3):
card1 = dbc.Card([
dbc.CardBody([
html.H4(f"{input1}", className="card-title"),
html.P(f"{input1} was submitted.")
],style={'display': 'inline-block',
'width': '33.3%',
'text-align': 'center',
'background-color': 'rgba(37, 150, 190)',
'color':'white',
'border': "2px solid white"})
])
card2 = dbc.Card([
dbc.CardBody([
html.H4(f"{input2}", className="card-title"),
html.P(f"{input2} was submitted.")
],style={'display': 'inline-block',
'width': '33.3%',
'text-align': 'center',
'background-color': 'rgba(37, 150, 190)',
'color':'white',
'border': "2px solid white"})
])
card3 = dbc.Card([
dbc.CardBody([
html.H4(f"{input3}", className="card-title"),
html.P(f"{input3} was submitted.")
],style={'display': 'inline-block',
'width': '33.3%',
'text-align': 'center',
'background-color': 'rgba(37, 150, 190)',
'color':'white',
'border': "2px solid white"})
])
return (card1, card2, card3)
if __name__ == "__main__":
app.run_server()
You haven't included the bootstrap styles:
Linking a stylesheet
dash-bootstrap-components doesn't come with CSS included. This is to give you the freedom to use any Bootstrap v4 stylesheet of your choice. This means however that in order for the components to be styled properly, you must link to a stylesheet yourself.
In Python, each CDN link is available within the dbc.themes submodule and can be used when instantiating the app object.
https://dash-bootstrap-components.opensource.faculty.ai/docs/quickstart/
So instead of this:
app = dash.Dash()
do this:
app = dash.Dash(external_stylesheets=[dbc.themes.BOOTSTRAP])

Django + plotly-dash: cannot render graphs side to side

I have followed this Subplot ( Side to side ) in python Dash and How to add multiple graphs to Dash app on a single browser page?, to find a way to get graphs rendering side to side in my template.
I cannot get it to work, the size of the graphs are adjusting well, but they keep rendering one below the other. I am confused about what is going wrong, and as I am just picking up dash, I am struggling to identify the root cause of the issue.
UPDATE: As adivced in the comments, i have tried including graph1 and graph2 inside as children of one div tag and display, however it still does not let get two graphs next to each other.
Here is what my file looks like:
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import plotly.graph_objs as go
from django_plotly_dash import DjangoDash
import pandas as pd
import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.express as px
from django_plotly_dash import DjangoDash
import dash_table
import os
#external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
external_stylesheets = 'home/ubuntu/exostocksaas/staticfiles/css/style.css'
app = DjangoDash('tryout', external_stylesheets=external_stylesheets)
# assume you have a "long-form" data frame
# see https://plotly.com/python/px-arguments/ for more options
df_bar = pd.DataFrame({
"Fruit": ["Apples", "Oranges", "Bananas", "Apples", "Oranges", "Bananas"],
"Amount": [4, 1, 2, 2, 4, 5],
"City": ["SF", "SF", "SF", "Montreal", "Montreal", "Montreal"]
})
fig = px.bar(df_bar, x="Fruit", y="Amount", color="City", barmode="group")
app.layout = html.Div(children=[
# All elements from the top of the page
html.Div(children=[
html.Div(children=[
html.H1('Hello Dash'),
html.Div(''' Dash: A web application framework for Python.'''),
dcc.Graph(id='graph1',figure=fig, style={"width":500, "margin": 10,'display': 'flex'}),
html.H3('Hello Dash'),
dcc.Graph(id='graph2',figure=fig, style={"width":500, "margin": 10,'display': 'flex'}),
],
),
html.Div(children=[
html.H1('Hello Dash', style={"width":500, "margin": 0,'display': 'flex'}),
html.Div('''Dash: A web application framework for Python.''', style={"width":500, "margin": 0,'display': 'inline-block'}),
dcc.Graph(id='graph2',figure=fig, style={"width":500, "margin": 0,'display': 'flex'}),
]),
html.H1('Hello Dash'),
html.Div('''Dash: A web application framework for Python.'''),
dcc.Graph(id='graph3',figure=fig, style={"width":500, "margin": 0,'display': 'flex'}
),
], className='row'),
html.Div([
html.H1(children='Hello Dash'),
html.Div(children='''
Dash: A web application framework for Python.
'''),
dash_table.DataTable(
id='table',
columns=[{"name": i, "id": i} for i in df_bar.columns],
data=df_bar.to_dict('records'),
sort_action='native',
filter_action='native',
export_format='csv',
style_cell={'textAlign': 'center', 'font-size' : '16px','width': '10px',
'overflow': 'hidden'
},
style_data_conditional=[
{
'if': {'row_index': 'odd'},
'backgroundColor': 'rgb(248, 248, 248)'
}
],
style_header={
'backgroundColor': 'rgb(230, 230, 230)',
'fontWeight': 'bold',
'font-size' : '20px'
}
)
], className='six columns')
])
still no luck, I can't find a way to get it to work
I ran this locally and it worked. I eliminated your stylesheets so I could show the CSS here using the style prop.
html.Div(children=[
html.Div(
style=dict(display='flex', height=500),
children=[
html.H1('Hello Dash'),
html.Div(''' Dash: A web application framework for Python.'''),
dcc.Graph(id='graph1', figure=fig,
style={"width": 500, "margin": 10, 'display': 'flex'}),
html.H3('Hello Dash'),
dcc.Graph(id='graph2', figure=fig,
style={"width": 500, "margin": 10, 'display': 'flex'}),
],
),
], className='row'),

Categories

Resources