Arranging elements horizontally in a dash application - python

I'm trying to develop a Dash application in python. I tried adding style={'display': 'inline-block'} to the html.Div() component, as well as to other components, but couldn't set the drop-down menus to align in one row.
The page looks as follows:
with the inline styling:
Without the inline styling:
The code in the question was given to me as a template that needs to be filled properly. The complex hierarchy was part of the template. My job is to add code as needed. I'm adding only the problematic part of the code (without the title and the graph elements that are seen in the images):
df = pd.read_csv("dash\Pricing Data.csv")
colors = {
'background': '#111111',
'text': '#7FDBFF'
}
boxplot_layout = (
dbc.Container(
[dbc.Row(
[
dbc.Col(
[
dbc.Card(
[
dbc.CardBody(
[
dbc.Row(
[
dbc.Col(
html.Div(
dbc.Row(
[
dbc.Col(
[
dcc.Dropdown(
id="aggregate-dropdown",
options=[
{
"label": "Total",
"value": "sum",
},
{
"label": "Average",
"value": "average",
},
],
value="sum",
style={
'textAlign': 'center',
# 'color': colors['text']
},
)
],
),
dbc.Col(
[
dcc.Dropdown(
id="y-dropdown",
options=[
{'label': i, 'value': i}
for i in df.columns],
style={
'textAlign': 'center',
},
value='Age'
)
],
),
dbc.Col(
[
html.Label(
"by",
style={
'textAlign': 'center',
# 'color': colors['text']
}
)
],
),
dbc.Col(
[
dcc.Dropdown(
id="x-dropdown",
options=[
{'label': i, 'value': i}
for i in df.columns],
style={
'textAlign': 'center',
'padding': '3px ',
},
value='Age'
)],),],)))],),])],inverse=True,)])])]))
app.layout = boxplot_layout
if __name__ == "__main__":
app.run_server(debug=True)
Also, as can be seen in the images, there's an error message. I couldn't find solutions for this error, so if you have any ideas regarding its cause or how to find it I'll be grateful if you could post it too.
Thanks.

Following the doc example:
dbc.Row(
[
dbc.Col(html.Div("One of three columns")),
dbc.Col(html.Div("One of three columns")),
dbc.Col(html.Div("One of three columns")),
]
),
it results something you are chasing for. So, that's the basic structure, removing unnecessary code, follows:
import dash
import dash_html_components as html
import dash_core_components as dcc
import dash_bootstrap_components as dbc
import pandas as pd
df = pd.read_csv()
colors = {
'background': '#111111',
'text': '#7FDBFF'
}
app = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP])
app.layout = html.Div([
dbc.Container([
dbc.Row([
dbc.Col(
html.Div([
dcc.Dropdown(
id="aggregate-dropdown",
options=[
{
"label": "Total",
"value": "sum",
},
{
"label": "Average",
"value": "average",
},
],
value="sum",
style={
'textAlign': 'center',
# 'color': colors['text']
},
)
]), width=3
),
dbc.Col(
html.Div([
dcc.Dropdown(
id="y-dropdown",
options=[
{'label': i, 'value': i}
for i in df.columns],
style={
'textAlign': 'center',
},
value='Age'
)
]), width=3
),
dbc.Col(
html.Div([
html.Label(
"by",
style={
'textAlign': 'center',
# 'color': colors['text']
}
)
]), width=1
),
dbc.Col(
html.Div([
dcc.Dropdown(
id="x-dropdown",
options=[
{'label': i, 'value': i}
for i in df.columns],
style={
'textAlign': 'center',
},
value='Age'
)
]), width=3
),
])
])
])
if __name__ == "__main__":
app.run_server(debug=True)
Note I passed a 'width=' keyword argument to set the size of columns.
And that's the result:
result
I hope it's that help you to find the better way to organize your code.

What I did eventually was to change the style inside the Column components of the Drop-down menus, as well as the style of the Drop-down themselves. I used the tags 'padding' and 'width' and changed their values until it looked OK. I also used the value 'inline-block' for the 'display' tag.
For instance, here's the code for one of the drop-down menus and it's column:
dbc.Col(
[
dcc.Dropdown(
id="y-axis-dropdown",
options=
[{'label': i, 'value': i} for i in df.columns],
value='Age',
style={'textAlign': 'center'}
)
], style={
'display': 'inline-block',
'width': '25%',
'padding': 30,
'textAlign': 'center'
}
)

Related

Python Dash app with excel-like feature to select column elements with dropdown

I am writing a dash app with following inputs like below:-
So far I've written the code as below:-
from dash import Dash, dcc, html, Input, Output, dash_table
import dash
from dash.dependencies import Input, Output, State
import dash
import pandas as pd
import dash_bootstrap_components as dbc
import io
import base64
import dash_renderer
def parse_contents(contents, filename):
# content_type, content_string = contents.split(',')
content_type, content_string = contents.split(',')
decoded = base64.b64decode(content_string)
df1 = pd.read_excel(io.BytesIO(decoded), sheet_name='Sheet1')
df2 = pd.read_excel(io.BytesIO(decoded), sheet_name='Sheet2')
return df1, df2
app = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP])
app.layout = dbc.Container([
dbc.Row(
dbc.Col(html.H1("Container Vulnerability Risk Rating Calculator",
className='text-center text-primary'),
width=12)
),
dbc.Row([
dcc.Upload(
id='upload-data',
children=html.Div([
'Drag and Drop or ',
html.A('Select Files')
]),
style={
'width': '30%',
'height': '40px',
'lineHeight': '40px',
'borderWidth': '1px',
'borderStyle': 'dashed',
'borderRadius': '5px',
'textAlign': 'center',
'margin': '0px'
},
multiple=False
)]
),
dbc.Row([
dbc.Col([
dash_table.DataTable(
id='no-dropdown',
fill_width=False,
columns=[
{'id': 'Microservices', 'name': 'Microservices'}
],
css=[ {"selector": ".Select-menu-outer", "rule": "display : block !important"} ],
style_cell={'textAlign': 'left'},
editable=False,
)
], width=5
),
dbc.Col([
dash_table.DataTable(
id='with-dropdown',
fill_width=False,
css=[ {"selector": ".Select-menu-outer", "rule": "display : block !important"} ],
# style_cell={'textAlign': 'left'},
columns=[
{'id': 'Hosting Environment', 'name': 'Hosting Environment', 'presentation': 'dropdown'},
{'id': 'Complexities', 'name': 'Complexities', 'presentation': 'dropdown'},
{'id': 'Criticality', 'name': 'Criticality', 'presentation': 'dropdown'}
],
editable=False,
)
], width=5
)
]
)
], fluid=True
)
#app.callback(
[
Output('no-dropdown', "data"),
Output('with-dropdown', 'dropdown'),
Output('with-dropdown', 'data')
],
Input('upload-data', 'contents'),
Input('upload-data', 'filename')
)
def load_data(contents, filename):
if contents is not None:
# contents = contents[0]
dff1, dff2 = parse_contents(contents, filename)
dropdown={
'Hosting Environment': {
'options': [
{'label': i, 'value': i} for i in dff2['Hosting Environment']
]
},
'Complexities': {
'options': [
{'label': i, 'value': i} for i in dff2['Complexities']
]
},
'Criticality': {
'options': [
{'label': i, 'value': i} for i in dff2['Criticality']
]
}
}
# print(dff['Hosting Environment'].unique())
return dff1['Microservices'].to_frame().to_dict('records'), dropdown, dff2[['Hosting Environment', 'Complexities', 'Criticality']].to_dict('records')
else:
# print(type([{}]))
return [{}], {}, [{}]
if __name__ == '__main__':
app.run_server(debug=True)
This program renders the Layout where the Microservices column renders fine as it has to be a static column but "Hosting Environment" and other columns highlighted in Yellow, should display a dropdown so that user can select various options.
I first thought that it's due to a bug in Bootstrap, which is well documented. but even after including the workaround code, this still doesn't work.
Any help would be greatly appreciated.

Divide my dashboard into two columns in Python Dash

I tried now for some time to divide my dashboard into two columns, with "Material1" centered in the first column, and "Material2" centered in the second column, keeping the graph as is (entire width) of this dashboard:
I tried dbc.col and dbc.Row methods to solve this, but haven't found the right way to do this.
Any help is highly appreciated!! :)
This is my code:
app.layout = html.Div([
# Input Row: Material 1
html.Div([
html.Label('Material 1'),
dcc.Dropdown(
id='dropdown1',
options=[{'label': k, 'value': k} for k in all_options.keys()],
value=options1[0],
style={'width': '400px', 'margin-left': 0}),
]),
html.Div([
html.Label('m3'),
daq.NumericInput(
id='numeric-input-1',
min=0,
max=200,
value=0,
style={'width': '200px', 'margin-left': 0}),
]),
# Input Row: Material 2
html.Div([
html.Label('Material 2'),
dcc.Dropdown(
id='dropdown2',
options=[{'label': k, 'value': k} for k in all_options.keys()],
value=options1[0],
style={'width': '400px', 'margin-left': 0}),
]),
html.Div([
html.Label('m3'),
daq.NumericInput(
id='numeric-input-2',
min=0,
max=200,
value=0,
style={'width': '200px', 'margin-left': 0}),
], style={'display': 'inline-block'}),
# Input: Indicator
html.Div([
html.Label('Indicator'),
dcc.Dropdown(
id='dropdown3',
style={'width': '400px', 'margin-left': 0}),
]),
#Graph
html.Div([
dcc.Graph(
id='display-selected-values',
style={'width': '2400px', 'margin-left': 0, 'columnCount': 1}),
])
])
it's all about being systematic (where code formatters help)
using dash 2.0.0 and dbc 1.0.0-b1
keep on embedding Row and Col as required to meet your layout requirements
import json
import numpy as np
import dash_bootstrap_components as dbc
import dash
from jupyter_dash import JupyterDash
all_options = {k: v for k, v in zip(list("ABCD"), np.random.randint(1, 4, 4))}
options1 = list(all_options.keys())
# Build App
app = JupyterDash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP])
app.layout = dash.html.Div(
[
dbc.Row(
[
dbc.Col(
dbc.Row(
[
dash.html.Label("Material 1"),
dash.dcc.Dropdown(
id="dropdown1",
options=[
{"label": k, "value": k} for k in all_options.keys()
],
value=options1[0],
style={"width": "400px", "margin-left": 0},
),
],
justify="center",
),
),
dbc.Col(
dbc.Row(
[
dash.html.Label("Material 2"),
dash.dcc.Dropdown(
id="dropdown2",
options=[
{"label": k, "value": k} for k in all_options.keys()
],
value=options1[0],
style={"width": "400px", "margin-left": 0},
),
],
justify="center",
),
),
],
justify="center",
),
dash.dcc.Graph(id="newCases", style={"height": "45vh"}),
],
style={"font-family": "Arial", "font-size": "0.9em", "text-align": "center"},
)
# Run app and display result inline in the notebook
app.run_server(mode="inline")

Aligning the height of the first and second column in Python Dash app

I have a probably simple problem that I cannot solve. I have two columns in my Python Dash dashboard, which are not aligned in height, see here:
What do I need to change in my code so that the two columns are on the same height?
Any help is much appreciated.
This is my code:
app = dash.Dash(__name__)
app.layout = html.Div([
html.Div([
html.Label('Material 1'),
dcc.Dropdown(
id='s1m1s',
options=[{'label': i, 'value': i} for i in available_indicators],
value=options1[0],
),
html.Label('Material 1'),
dcc.Dropdown(
id='s1mdf45',
options=[{'label': i, 'value': i} for i in available_indicators],
value=options1[0],
),
], style={'width': '20%', 'display': 'inline-block'}),
html.Div([
html.Label('m3'),
daq.NumericInput(
id='s2m1_num',
min=0,
max=200,
value=0,
),
html.Label('m3'),
daq.NumericInput(
id='s2m2_num',
min=0,
max=200,
value=0,
),
], style={'width': '20%', 'display': 'inline-block'})
])
You can add 'vertical-align': 'top' to the style dictionaries of the two columns to make sure that they are aligned at the top, see below.
import dash
import dash_html_components as html
import dash_core_components as dcc
import dash_daq as daq
app = dash.Dash(__name__)
app.layout = html.Div([
# first column
html.Div(
children=[
html.Label('Material 1'),
dcc.Dropdown(
id='s1m1s',
options=[{'label': i, 'value': i} for i in ['option_1', 'option_2', 'option_3']],
value='option_1',
),
html.Label('Material 1'),
dcc.Dropdown(
id='s1mdf45',
options=[{'label': i, 'value': i} for i in ['option_1', 'option_2', 'option_3']],
value='option_2',
),
],
style={
'width': '20%',
'display': 'inline-block',
'vertical-align': 'top',
}
),
# second column
html.Div(
children=[
html.Label('m3'),
daq.NumericInput(
id='s2m1_num',
min=0,
max=200,
value=0,
),
html.Label('m3'),
daq.NumericInput(
id='s2m2_num',
min=0,
max=200,
value=0,
),
],
style={
'width': '20%',
'display': 'inline-block',
'vertical-align': 'top',
}
)
])
if __name__ == '__main__':
app.run_server(debug=True, host='127.0.0.1')

Adjust width of dropdown menu option in Dash-Plotly

I am trying to build an app using Dash in Python based on Plotly. I am having hard time in adjusting the width of Dropdown menu options. I have attached code and image below. I would like the width of Dropdown options to be same as the menu width.
app.layout = html.Div(children=[
html.H1(children='Welcome to Portfolio Construction Engine!'),
html.Div(children='What would you like to do?', style={
'font-style': 'italic',
'font-weight': 'bold'
}),
html.Div([
dcc.Dropdown(
id='demo-dropdown',
options=[
{'label': 'Upload Scores', 'value': 'upload_scores'},
{'label': 'Analyze Portfolios', 'value': 'analyze_portfoliio'},
{'label': 'Generate Data for IC Engine', 'value': 'gen_data_ic_engine'}
],
placeholder='Select a task...',
style={
'width': '50%'
}
),
html.Div(id='dd-output-container')
])
])
While its correct to place width: 50% to change the width of the dropdown component, you've placed it in the inner component rather than the parent Div.
app.layout = html.Div(
children=[
html.H1(children="Welcome to Portfolio Construction Engine!"),
html.Div(
children="What would you like to do?",
style={"font-style": "italic", "font-weight": "bold"},
),
html.Div(
[
dcc.Dropdown(
id="demo-dropdown",
options=[
{"label": "Upload Scores", "value": "upload_scores"},
{"label": "Analyze Portfolios", "value": "analyze_portfoliio"},
{
"label": "Generate Data for IC Engine",
"value": "gen_data_ic_engine",
},
],
placeholder="Select a task...",
# style={"width": "50%"}, NOT HERE
),
html.Div(id="dd-output-container"),
],
style={"width": "50%"},
),
]
)

Layout and Dropdown menu in Dash - Python

I cannot seem to be able to get the layout of my dropdown menu boxes correctly. Basically I want for the dropdown box to be on the right of their matching question and on the same line.
Can anyone help please?
I have tried multiple combinations of style={'display': 'inline-block', 'width:'X%'} and className = 'X columns' with no luck.
import dash
from dash.dependencies import Input, Output, State
import dash_core_components as dcc
import dash_html_components as html
import dash_auth
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
app.layout = html.Div([
html.Div(
[
html.Div(
[
html.H6("""Select your current industry""",
style={'textAlign': 'right', 'font-weight':'bold', 'margin-left': '0em', 'margin-right': '2em', 'display': 'inline-block', 'width': '40%'})
],
),
dcc.Dropdown(
id = 'business_area_dropdown',
options=[
{'label': 'Academia', 'value': 'academia'},
{'label': 'Energy', 'value': 'energy'},
{'label': 'Research', 'value': 'research'}
],
placeholder="Select Business Area",
style = dict(
width = '40%',
display = 'inline-block',
verticalAlign = "middle"
)
)
],
className='row'
),
html.Div(
[
html.Div(
[
html.H6("""Are you happy where you are?""",
style={'textAlign': 'right', 'font-weight':'bold', 'margin-left': '0em', 'margin-right': '2em', 'display': 'inline-block', 'width': '40%'})
],
),
dcc.Dropdown(
id = 'search_preference',
options=[
{'label': 'Yes', 'value': 'yes'},
{'label': 'No', 'value': 'no'}
],
placeholder="Select Answer",
style = dict(
width = '40%',
display = 'inline-block',
verticalAlign = "middle"
)
)
],
className='row'
),],
style={'display': 'inline-block', 'backgroundColor': '#fff7dd', 'width': '99%'}
)
if __name__ == '__main__':
app.run_server()
The dropdown boxes appear in a completely different line. I'd like for the dropdown boxes to be aligned horizontally to their respective questions to be answered.
My favorite styling trick, Flexbox, is how I would solve this one.
app.layout = html.Div([
html.Div(
[
html.Div(
[
html.H6("""Select your current industry""",
style={'margin-right': '2em'})
],
),
dcc.Dropdown(
id='business_area_dropdown',
options=[
{'label': 'Academia', 'value': 'academia'},
{'label': 'Energy', 'value': 'energy'},
{'label': 'Research', 'value': 'research'}
],
placeholder="Select Business Area",
style=dict(
width='40%',
verticalAlign="middle"
)
)
],
style=dict(display='flex')
),
html.Div(
[
html.Div(
[
html.H6("""Are you happy where you are?""",
style={'margin-right': '2em'})
],
),
dcc.Dropdown(
id='search_preference',
options=[
{'label': 'Yes', 'value': 'yes'},
{'label': 'No', 'value': 'no'}
],
placeholder="Select Answer",
style=dict(
width='40%',
display='inline-block',
verticalAlign="middle"
)
)
],
style=dict(display='flex')
), ],
)
And here is a screenshot of the results:

Categories