Related
I am trying to make a dashboard with dash in python and I am trying to align 2 dropdowns and a button horizontally
this is the html.Div that I am working with
html.Div([
html.Div(
dcc.Dropdown(
id='dropdown 1',
options=list(df_.columns),
multi=True,
clearable=True,
searchable=True,
placeholder='Required Rows',
optionHeight=20,
), style={
'width': '39%',
'display': 'inline-block',
'vertical-align': 'top',
}
),
html.Div(
dcc.Dropdown(
id='dropdown 2',
options=list(df_.columns),
multi=True,
clearable=True,
searchable=True,
placeholder='Required Columns',
optionHeight=20,
), style={
'width': '39%',
'display': 'inline-block',
'vertical-align': 'top',
}
),
html.Div(
html.Button(
"Do something",
id='button_1',
), style={
'width': '20%',
'display': 'inline-block',
'vertical-align': 'top'
}
)
]),
Is there any way to make the height of the do something button the same as that of the dropdown even when the window is resizing.
Or
Is there any way to make the height of dropdowns same as that of the button, which stays the same even when resizing?
Thank you
You can set the elements to the same line-height.
I'm trying to build a Dashboard using Plotly in Python. I've initialized a dashboard, and divided it into portions/containers using 'dash_html_components.Div()'. Later, I've used 'dash_core_components.Graph()' to plot graph inside a div. The problem arises when I try to plot a graph inside a div, the plot actually goes outside the div size/container. Though the graph maintains width, but not the height. I have added comments, where is necessary.
This is the image of my dashboard, and the portion that is ticked, there I want to place a graph.
Dashboard without graph:
Dashboard with graph:
Code:
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State
import plotly.graph_objs as go
# import pandas_datareader.data as web # requires v0.6.0 or later
from datetime import datetime
import pandas as pd
from datetime import datetime
#building Dashboard
app = dash.Dash()
app.layout = html.Div([ #(row=main, col=main) block
html.Div([ ##(row=1, col=1) block
], style = { ##(row=1, col=1) block style
'display': 'block',
'float': 'left',
# 'margin': 'auto',
'width': '25%',
'height': '50%',
# 'border': '1px solid #006600',
'background-color': 'cyan'
}),
html.Div([ ##(row=1, col=2) block
#graph containing div
dcc.Graph(
id = 'my_graph',
figure={
'data': [go.Scatter(
x = [0,1],
y = [0,1],
mode = 'lines'
)],
'layout': go.Layout(
title = 'graph',
autosize = True
)
}
)
], style = { ##(row=1, col=2) block style
'display': 'block',
'float': 'left',
# 'margin': 'auto',
'width': '25%',
'height': '50%',
# 'border': '1px solid #006600',
'background-color': 'DarkCyan'
}),
html.Div([ ##(row=1, col=3) block
], style = { ##(row=1, col=3) block sty;e
'display': 'block',
'float': 'left',
# 'margin': 'auto',
'width': '50%',
'height': '50%',
# 'border': '1px solid #006600',
'background-color': 'MediumSeaGreen'
})
], style = { #(row=main, col=main) block style
'display': 'block',
'float': 'center',
'margin': '-1vw auto',
# 'margin': '-1vw 11vw 0 11vw',
'width': '70vw',
'height': '30vw',
# 'border': '1px solid #006600',
'background-color': 'gray',
'box-shadow': '10px 10px 5px gray'
})
if __name__ == '__main__':
app.run_server(port=1000)
You need to specify a style value for your dcc.Graph if you want it to fit according to the html layout. In this case, you can do:
dcc.Graph(
id="my_graph",
figure={
"data": [go.Scatter(x=[0, 1], y=[0, 1], mode="lines")],
"layout": go.Layout(title="graph", autosize=True),
},
style={'height': '100%'}
)
I am wondering if there is a way that you can have a dash table scroll vertically up and down automatically when the scroll bar is available.
This is a simple example (I used the same dataframe 7 times to make it long enough).
import dash
import dash_table
import pandas as pd
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/solar.csv')
long_data = pd.concat([df,df,df,df,df,df,df])
app = dash.Dash(__name__)
app.layout = dash_table.DataTable(
id='table',
columns=[{"name": i, "id": i} for i in long_data.columns],
data=long_data.to_dict('records'),
)
if __name__ == '__main__':
app.run_server(debug=False)
Is there a way to make what's on this page go vertically up and down?
I'm not sure if this is what you're looking for, but you can make the table scrollable via style_table (reference):
app.layout = dash_table.DataTable(
id='table',
columns=[{"name": i, "id": i} for i in long_data.columns],
data=long_data.to_dict('records'),
style_table={
'overflowY': 'scroll'
}
)
If you're looking to have the table scroll automatically at a given speed, I doubt dash/plotly has in-built functionality to do that.
Have you attempted to use "overflow":"Scroll" or overflowY
Example:
dbc.Col(
html.Div(id='timeline-div',),
width=4,
style={'width': '100%',
'height': '750px',
'overflow': 'scroll',
'padding': '10px 10px 10px 20px'
}
),
Resource: https://community.plotly.com/t/how-to-make-a-data-table-scrollable-with-using-overflowy-but-without-the-double-scroll-bars/27920
Issue Fixed :-
style_header=
{
'fontWeight': 'bold',
'border': 'thin lightgrey solid',
'backgroundColor': 'rgb(100, 100, 100)',
'color': 'white'
},
style_cell={
'fontFamily': 'Open Sans',
'textAlign': 'left',
'width': '150px',
'minWidth': '180px',
'maxWidth': '180px',
'whiteSpace': 'no-wrap',
'overflow': 'hidden',
'textOverflow': 'ellipsis',
'backgroundColor': 'Rgb(230,230,250)'
},
style_data_conditional=[
{
'if': {'row_index': 'odd'},
'backgroundColor': 'rgb(248, 248, 248)'
},
{
'if': {'column_id': 'country'},
'backgroundColor': 'rgb(255, 255, 255)',
'color': 'black',
'fontWeight': 'bold',
'textAlign': 'center'
}
],
fixed_rows={'headers': True, 'data': 0}
You can accomplish this using callbacks and dcc.interval, but it is clunky!
Hello I am working on a dash app, and somehow I am not able to update graphs between different divs callback. This is how the app works:
The user gives a url input on the frontend in a textinput box and button is clicked to run analysis.
The user can select the view mode as well before running the analysis, The view mode depends on the dropdown selector
The url is used to display a video frame and run a python function.
The processed results should be stored in the dcc.store component.
The stored data is then called in to update the graphs.
Below is the callback codes:
#Video Selection
#app.callback(Output("video-display", "url"),
[Input("submit_button", "n_clicks")],
[State('video_url', 'value')])
def select_footage(n_clicks, video_url):
if n_clicks is not None and n_clicks > 0:
url = video_url
return url
# Processing and Storing the results in dcc.store
#app.callback(Output("intermediate-value", "data"),
[Input("submit_button", "n_clicks")],
[State('video_url', 'value')])
def video_processing(n_clicks, value ):
global frame
if n_clicks is not None and n_clicks > 0:
frame = python_func(url)
return frame.to_json(orient='split')
# Callback to change the graph view mode div
#app.callback(Output("div-graph-mode", "children"),
[Input("dropdown-graph-view-mode", "value")])
def update_graph_mode(value):
if value == "graphical":
return [
html.Div(
children=[
html.P(children="Retention Score of Detected Labels",
className='plot-title'),
dcc.Graph(
id="bar-score-graph",
style={'height': '55vh', 'width': '100%'}
),
html.P(children="Audience Retention Behavior",
className='plot-title'),
dcc.Graph(
id="line_chart_retention",
style={'height': '45vh', 'width': '100%'}
)
]
)
]
else:
return []
#app.callback(Output("div-table-mode", "children"),
[Input("dropdown-graph-view-mode", "value")])
def update_table_mode(dropdown_value):
if dropdown_value == "table":
return [
html.Div(
children=[
html.P(children="Retention By Label",
className='plot-title'),
html.Div([
table.DataTable(
id="label_retention",
)],
style={'height': '45vh'}),
html.P(children="Retention by Time Stamp",
className='plot-title'),
html.Div([
table.DataTable(
id="timestamp_retention",
style_table={'maxHeight': '40vh', 'width': '100%', 'overflowY': 'scroll'})],
style={'height': '40vh'}
)
]
)
]
else:
return []
# Updating Graphs
#app.callback(Output("label_retention", "figure"),
[Input("dropdown-graph-view-mode", "value")])
def update_table_bar(value):
global frame
if frame is not None:
print(frame)
print("table")
print(value)
#app.callback(Output("bar-score-graph", "figure"),
[Input("dropdown-graph-view-mode", "value")])
def update_score_bar(value):
global frame
if frame is not None:
print(frame)
print("graph")
print(value)
Now what happens is that if I try to toggle between the two graph view modes, the app does not reflect the graphs and requires to click on the button again to get the results. So, basically I believe the data does not gets lost in the dcc.store component when I toggle with the dropdowns.
How can I make the app behave in a way that my python function runs only once on the submit button, but then I am able to toggle between the view modes to see the graphs.
Thanks a lot in advance!!
P.S. This is just a snippet of codes, as the code is too long, but please let me know if you would want to see the entire code.
UPDATE: I have just realised that when I select the Graph Mode, the app prints the results for Table Mode and when I select the table model, the app prints the results for graph mode. I am not able to figure out as to why this is happening.
I was finally able to resolve my issue as below:
#app.callback(Output("div-table-mode", "children"),
[Input("dropdown-graph-view-mode", "value")])
def update_table_mode(dropdown_value):
if dropdown_value == "tabular":
return [
html.Div(
children=[
html.P(children="Retention By Label",
className='plot-title', style={'margin': '0 0 1em 0'}),
html.Div([
table.DataTable(
id="label_retention",
columns=[{"name": i, "id": i} for i in label_retention.columns],
data=label_retention.to_dict("rows"),
style_table={'maxHeight': '40vh', 'width': '100%', 'overflowY': 'scroll'},
style_cell_conditional=[
{
'if': {'column_id': c},
'textAlign': 'left'
} for c in ['Labels']
],
style_data_conditional=[
{
'if': {'row_index': 'odd'},
'backgroundColor': 'rgb(248, 248, 248)'
}
],
style_header={
'backgroundColor': 'rgb(230, 230, 230)',
'fontWeight': 'bold'
}
)],
style={'height': '40vh'}),
html.P(children="Retention by Time Stamp",
className='plot-title', style={'margin': '1em 0 1em 0'}),
html.Div([
table.DataTable(
id="timestamp_retention",
columns=[{"name": i, "id": i} for i in timeline_retention.columns],
data=timeline_retention.to_dict("rows"),
style_table={'maxHeight': '40vh', 'width': '100%', 'overflowY': 'scroll'},
style_cell={'textAlign': 'left', 'minWidth': '20px', 'width': '20px', 'maxWidth': '50px',
'whiteSpace': 'normal'},
css=[{
'selector': '.dash-cell div.dash-cell-value',
'rule': 'display: inline; white-space: inherit; overflow: inherit; text-overflow: inherit;'
}],
style_data_conditional=[
{
'if': {'row_index': 'odd'},
'backgroundColor': 'rgb(248, 248, 248)'
}
],
style_header={
'backgroundColor': 'rgb(230, 230, 230)',
'fontWeight': 'bold'
}
)],
style={'height': '40vh'}
)
],
style={'backgroundColor': '#F2F2F2'}
)
]
else:
return []
#app.callback(Output("div-graph-mode", "children"),
[Input("dropdown-graph-view-mode", "value")])
def update_graph_mode(value):
if value == "graphical":
return [
html.Div(
children=[
html.P(children="Retention Score of Detected Labels",
className='plot-title', style={'margin': '0 0 1em 0', 'width': '100%'}),
dcc.Graph(
id="bar-score-graph",
figure=go.Figure({
'data': [{'hoverinfo': 'x+text',
'name': 'Detection Scores',
#'text': y_text,
'type': 'bar',
'x': label_retention["Description"],
'marker': {'color': colors},
'y': label_retention["sum"].tolist()}],
'layout': {'showlegend': False,
'autosize': False,
'paper_bgcolor': 'rgb(249,249,249)',
'plot_bgcolor': 'rgb(249,249,249)',
'xaxis': {'automargin': True, 'tickangle': -45},
'yaxis': {'automargin': True, 'range': [minval, maxval], 'title': {'text': 'Score'}}}
}
),
style={'height': '55vh', 'width': '100%'}
),
html.P(children="Audience Retention Behavior",
className='plot-title', style={'margin': '0 0 1em 0', 'width': '100%'}),
dcc.Graph(
id="line_chart_retention",
figure=go.Figure({
'data': [go.Scatter(x=label_retention['Start'], y=label_retention['sum'], mode='lines', name='Audience Retention',
line=dict(color='firebrick', width=4))],
'layout': {
'yaxis': {'title': {'text': 'Audience Retention'}, 'automargin': True},
'xaxis': {'title': {'text': 'Time Segment'}, 'automargin': True},
'paper_bgcolor': 'rgb(249,249,249)',
'plot_bgcolor': 'rgb(249,249,249)',
}
}),
style={'height': '45vh', 'width': '100%'}
)
],
style={'backgroundColor': '#F2F2F2', 'width': '100%'}
)
]
else:
return []
I am working on plotly dash app. I have an almost working example. The only thing that is not working is that I am not able to restrict the functions defined in the callbacks not to run when the page loads.
I have tried add checks for the n_clicks inside the callback however it doesnt seem to be working. It runs the function without the clicks as well
Below is the code for the dash
from datetime import date
import base64
import dash
import plotly
import dash
from dash.dependencies import Input, Output, State
from plotly.graph_objs import *
from datetime import datetime as dt
import dash_html_components as html
import dash_core_components as dcc
import flask
import pandas as pd
server = flask.Flask('app')
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash('app', server=server, external_stylesheets=external_stylesheets)
app.layout = html.Div(style={'backgroundColor': '#EFEAEA', 'margin': '0px', 'padding': '0px'}, children=[
html.Div([
html.Div([
html.Img(src='data:image/png;base64,{}'.format(encoded_image.decode()),
style={'width': '200px', 'height': '100px', 'display': 'inline-block', 'float': 'left', 'padding-left': '5px', 'padding-top': '5px'})
]),
html.Div([
html.Div([
html.Div([
dcc.Dropdown(
id='demographics',
options=[
{'label': 'All 18-49', 'value': '18_39'},
{'label': 'Female 25-54', 'value': '25_54 F'},
{'label': 'All 25-54', 'value': '25-54'},
],
placeholder="Select Demographics",
)
],
style={'width': '30.5%', 'display': 'inline-block', 'padding-right': '10px'}),
html.Div([
dcc.DatePickerRange(
id='my-date-picker-range',
start_date_placeholder_text="Select a Start Date",
end_date_placeholder_text="Select an End Date",
min_date_allowed=dt(2018, 1, 1),
max_date_allowed=dt(2050, 12, 31),
initial_visible_month=dt(2019, 1, 2),
style={'width': '600', 'display': 'inline-block', 'padding-right': '10px'}
),
html.Div(id='output-container-date-picker-range')
],
style={'width': '30.3%', 'display': 'inline-block', 'padding-right': '10px', 'position': 'relative'})
],
style={
'backgroundColor': '#EFEAEA',
'padding': '5px 10px'}),
html.Div([
html.Div([
dcc.Dropdown(
id='Horsepower',
options=[
{'label': '200', 'value': 'two_hundred'},
{'label': '250', 'value': 'two_hundred_fifty'},
{'label': '300', 'value': 'three_hundred'},
{'label': '350', 'value': 'three_hundred_fifty'},
{'label': '400', 'value': 'four_hundred'}
],
placeholder="Select TARP",
)
],
style={'width': '20%', 'display': 'inline-block', 'padding-right': '10px'}),
html.Div([
dcc.Dropdown(
id='Kilometers',
options=[
{'label': '250,000', 'value': 250000, 'type': 'number'},
{'label': '500,000', ''value': 500000, 'type': 'number'},
{'label': '750,000', 'value': 750000, 'type': 'number'},
{'label': '1,000,000', 'value': 1000000, 'type': 'number'},
],
placeholder="Select Impressions",
)
],
style={'width': '20%', 'display': 'inline-block', 'padding-right': '10px'}),
html.Div([
dcc.Dropdown(
id='Speed',
options=[
{'label': 'Low', 'value': 50, 'type': 'number'},
{'label': 'Average', 'value': 100, 'type': 'number'},
{'label': 'High', 'value': 150, 'type': 'number'},
],
placeholder="Select Frequency",
)
],
style={'width': '20%', 'display': 'inline-block', 'padding-right': '10px'}),
html.Div([
html.Button('Submit', id='submit_button', type='submit', n_clicks=1,
style={'width': '100px', 'height': '34.5px', 'margin-bottom': '8px',
'border-radius': '4px', 'display': 'inline-block', 'background-color': '#2D91C3', 'color': 'white'})
],
style={'display': 'inline-block', 'padding-bottom': '20px', 'verticalAlign': 'middle'}),
], style={
'backgroundColor': '#EFEAEA',
'padding': '5px'})
], style={'position': 'relative', 'left': '250px'})
]),
html.Div([
html.Div([
dcc.Graph(id='example-graph', config={'modeBarButtonsToRemove': ['pan2d', 'lasso2d', 'sendDataToCloud',
'select2d', 'autoScale2d', 'resetScale2d',
'toggleSpikelines',
'hoverClosestCartesian']})
],
style={'width': '49.3%', 'display': 'inline-block', 'border': 'thin grey solid', 'margin-left': '5px',
'margin-right': '2.5px', 'margin-top': '5px', 'margin-bottom': '2.5px'}),
html.Div([
dcc.Graph(id='example-graph1')
],
style={'width': '49.3%', 'display': 'inline-block', 'border': 'thin grey solid', 'margin-left': '2.5px',
'margin-right': '5px', 'margin-top': '5px', 'margin-bottom': '2.5px', 'backgroundColor': '#EFEAEA'})
], style={'backgroundColor': '#EFEAEA'}),
html.Div([
dcc.Graph(id='graph1')
],
style={'width': '99.2%', 'height': '120%', 'display': 'inline-block', 'border': 'thin grey solid', 'margin-left': '2.5px',
'margin-right': '5px', 'margin-top': '5px', 'margin-bottom': '2.5px', 'backgroundColor': '#EFEAEA'})
])
#app.callback(Output('example-graph1', 'figure'),
[Input('submit_button', 'n_clicks')],
[State('my-date-picker-range', 'start_date'),
State('my-date-picker-range', 'end_date')])
def update_graph(n_clicks, start_date, end_date):
if n_clicks > 0:
df = df_new
start_date_temp = dt.strptime(start_date, '%Y-%m-%d')
end_date_temp = dt.strptime(end_date, '%Y-%m-%d')
start_date_new = start_date_temp.replace(start_date_temp.year - 1)
end_date_new = end_date_temp.replace(end_date_temp.year - 1)
end_date_string = end_date_new.strftime('%Y-%m-%d')
start_date_string = start_date_new.strftime('%Y-%m-%d')
mask = (df['Date'] >= start_date_string) & (df['Date'] <= end_date_string)
filtered_df = df.loc[mask]
trace = Scatter(
y=filtered_df['Weights'],
x=filtered_df['Date'],
line=plotly.graph_objs.scatter.Line(
color='#42C4F7'
),
hoverinfo='skip',
error_y=plotly.graph_objs.scatter.ErrorY(
type='data',
array=filtered_df['Gender'],
thickness=1.5,
width=2,
color='#B4E8FC'
),
mode='lines'
)
layout1 = Layout(
height=450,
xaxis=dict(
showgrid=False,
showline=False,
zeroline=False,
fixedrange=True,
title='Time Elapsed (sec)'
),
yaxis=dict(
showline=False,
fixedrange=True,
zeroline=False,
),
margin=plotly.graph_objs.layout.Margin(
t=45,
l=50,
r=50
)
)
return Figure(data=[trace], layout=layout1)
else:
return {"I am the boss"}
The reason I presume the n_clicks checks is not working because I get the following error
TypeError: strptime() argument 1 must be str, not None
I believe the error is because of the below code inside the function as the first time the page loads start_date would be none type.
start_date_temp = dt.strptime(start_date, '%Y-%m-%d')
Can some one please help to resolve the issue. What I expect that when the page loads the call back function should not run.
Thanks a lot in advance !!
Here is your problem:
html.Button('Submit', id='submit_button', type='submit', n_clicks=1,
You've preset n_clicks to have a value. Just remove that n_clicks=1 part, and it will load the page as None. You will then need to check n_clicks like this (or similar):
if n_clicks is not None and n_clicks > 0:
It worked for me, and ran until it broke with my example df.