Dash dashboard shows blank figure - python

I want to create a map that shows specified locations using Dash. I prepared a script:
import dash
import dash_core_components as dcc
import dash_html_components as html
mapbox_access_token = 'pk.eyJ1IjoiYWxpc2hvYmVpcmkiLCJhIjoiY2ozYnM3YTUxMDAxeDMzcGNjbmZyMmplZiJ9.ZjmQ0C2MNs1AzEBC_Syadg'
app = dash.Dash()
server = app.server
app.layout = html.Div([
dcc.Graph(
id='simple-map',
figure=dict(
data=dict(
lat=[51.98799603],
lon=[5.922999562],
type='scattermapbox',
marker=dict(size=5, color='white', opacity=0)
),
layout=dict(
mapbox=dict(
layers=[],
accesstoken=mapbox_access_token,
style='light',
center=dict(
lat=52.370216,
lon=-4.895168,
),
pitch=0,
zoom=2.5
)
)
)
)
])
app.css.append_css({
'external_url': 'https://codepen.io/chriddyp/pen/bWLwgP.css'
})
if __name__ == '__main__':
app.run_server(debug=True)
However, I am getting this result:
What am I doing wrong?

The solution is always simpler than it seemed. You have to add brackets to the data and to the marker.
import dash
import dash_core_components as dcc
import dash_html_components as html
mapbox_access_token = 'pk.eyJ1IjoiYWxpc2hvYmVpcmkiLCJhIjoiY2ozYnM3YTUxMDAxeDMzcGNjbmZyMmplZiJ9.ZjmQ0C2MNs1AzEBC_Syadg'
app = dash.Dash()
server = app.server
app.layout = html.Div([
dcc.Graph(
id='simple-map',
figure=dict(
data=[dict(
lat=[51.98799603],
lon=[5.922999562],
type='scattermapbox',
marker=[dict(size=5, color='white', opacity=0)]
)],
layout=dict(
mapbox=dict(
layers=[],
accesstoken=mapbox_access_token,
style='light',
center=dict(
lat=52.370216,
lon=-4.895168,
),
pitch=0,
zoom=2.5
)
)
)
)
])
app.css.append_css({
'external_url': 'https://codepen.io/chriddyp/pen/bWLwgP.css'
})
if __name__ == '__main__':
app.run_server(debug=True)
And the results is:

Related

There is a Horizontal Scrollbar dasboard plotly

I am building a dashboard with multi-Page Apps plotly and bootstrap. There is a horizontal scrollbar overflow on my website. I am looking to remove a scroll bar, and remove this blank space after imagen, thank you.
Here is the code:
App:
import pandas as pd
from dash_auth import BasicAuth
from dash import Dash, dcc, html, Input, Output, callback
from dash_extensions.enrich import ServersideOutput, DashProxy, ServersideOutputTransform
import dash_bootstrap_components as dbc
from pages import test, error_404
df = pd.read_parquet('dataset.parquet.gzip')
external_stylesheets = [
dbc.themes.BOOTSTRAP,
dbc.icons.BOOTSTRAP,
]
app = Dash(__name__, title = 'Test',
external_stylesheets=external_stylesheets,
suppress_callback_exceptions=True,
)
server = app.server
app.layout = html.Div([
dcc.Location(id="url", pathname="", refresh=False),
# Header
dbc.Row([
dbc.Col(html.A(
html.Img(src=app.get_asset_url("leters.jpg"), className="img-fluid brand-other"),
id="logo",
href="https://www.leters.com/", target="blank"
), width='12', class_name='justify-content-end d-flex'),
]),
html.Div(id='page-content'),
], className='col-12 col-lg-12')
#callback(
Output(component_id='page-content', component_property='children'),
Input(component_id='url', component_property='pathname')
)
def routing(path):
print(path)
if path == "":
return test.test
else:
return error_404
if __name__ == "__main__":
app.run_server(debug=True)
test:
from dash import html
test = html.Div([
html.H3("test", className="sub_title"),
])
I think you should change from html.Div to dbc.Container as below:
app.layout = dbc.Container([
dcc.Location(id="url", pathname="", refresh=False),
# Header
dbc.Row([
dbc.Col(html.A(
html.Img(src=app.get_asset_url("leters.jpg"), className="img-fluid brand-other"),
id="logo",
href="https://www.leters.com/", target="blank"
), width='12', class_name='justify-content-end d-flex'),
]),
html.Div(id='page-content'),
], fluid=True)
Hope this help.

How to use dbc.Row effectively?

I'm building an app with dash-plotly but i'm confused about how to the layer correctly the items.
import dash
import dash_bootstrap_components as dbc
from dash import html
from dash import dcc
app = dash.Dash(__name__)
app.layout = html.Div([
dbc.Row([ #row 1
dcc.Input(type='text'),
html.Button('A button'),
]),
html.Br(),
dbc.Row([ #row 2
dcc.Dropdown(['0','1', '2','3','4','5','6','7','8','9','10'],
'1',
style={
'width':'10%'}),
html.Button('A Button'),
])
])
if __name__ == '__main__':
app.run_server(debug=True)
The items in row #1 are inline, but the items in row #2 are stacked on each other. Both rows are composed with different elements, so how to impose the items in row #2 to be inline? What are the rules regarding dbc.Row ?
I think the problem here that you are using dash bootstrap components but with default stylesheet and I think you should combine dbc.Col with dbc.Row to make better layout. Here is the sample code:
import dash
import dash_bootstrap_components as dbc
from dash import html
from dash import dcc
app = dash.Dash(__name__,external_stylesheets=[dbc.themes.LUX])
app.layout = html.Div([
dbc.Row([
dbc.Col([
dcc.Input(type='text')
],width={'size':1,'offset':0,'order':'1'}),
dbc.Col([
html.Button('A button'),
],width={'size':1,'offset':0,'order':'1'})
]),
html.Br(),
dbc.Row([
dbc.Col([
dcc.Dropdown(['0','1', '2','3','4','5','6','7','8','9','10'],
'1'),
],width={'size':1,'offset':0,'order':'1'}),
dbc.Col([
html.Button('A Button'),
],width={'size':1,'offset':0,'order':'1'})
])
])
if __name__ == '__main__':
app.run_server(debug=True)
As you see, I added external_stylesheets=[dbc.themes.LUX] and added dbc.Col to the layout.
You can also use Bootstrap 5 instead using dash bootstrap components library likewise -
import dash
import dash_bootstrap_components as dbc
from dash import html
from dash import dcc
app = dash.Dash(__name__, external_stylesheets = ["https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css"])
app.layout = html.Div([
html.Div([
html.Div(
dcc.Input(id = "input-1", type = "text", placeholder = "Enter", className = "form-control"),
className = "col-lg-5"),
html.Div(
html.Button("Submit", id = "submit-1", className = "btn btn-dark"),
className = "col-lg-3"),
], className = "row row-cols-auto mb-4"),
html.Div([
html.Div(
dcc.Dropdown(['0','1', '2','3','4','5','6','7','8','9','10'],
'1'),
className = "col-lg-5"),
html.Div(
html.Button("Submit", id = "submit-2", className = "btn btn-dark"),
className = "col-lg-3"),
], className = "row row-cols-auto")
], className = "container-fluid mt-2")
if __name__ == '__main__':
app.run_server(debug=True)[![Sample][1]][1]

How to use Long_callback with multipage app in Dash Plotly?

I'm trying to build a multi page Dash App with Long Callback . When I run the app with Single page Application , it is working fine .Working code is given Below
SinglePage.py
import json
import dash
from dash import html, dcc
from dash.long_callback import DiskcacheLongCallbackManager
from dash.dependencies import Input, Output
import dash_bootstrap_components as dbc
import datetime
import pandas as pd
import plotly.express as px
## Diskcache
import diskcache
from query_4_entity_explr import get_ORG_info, get_daterange_entity_dataframe
cache = diskcache.Cache("./cache")
long_callback_manager = DiskcacheLongCallbackManager(cache)
app = dash.Dash("topx_org",
long_callback_manager=long_callback_manager,
external_stylesheets=[dbc.themes.BOOTSTRAP],
meta_tags=[{'name': 'viewport', 'content': 'initial-scale=1'}])
today = datetime.datetime.today().date()
date_30_day_back = (datetime.datetime.today() - datetime.timedelta(days=1)).date()
app.layout = dbc.Container([
dbc.Row([
dbc.Col(html.H3("Explore Organizations mentioned in media", className='text-center text-primary py-5'), width=12)
]),
dbc.Row([
dbc.Col(dbc.Label(['Select daterange']), width={'size': 2, 'offset': 0}),
dbc.Col(dcc.DatePickerRange(id='input_date_picker_range', display_format='YYYY-MM-DD', start_date=date_30_day_back, end_date=today), width={'size':10, 'offset':0}),
], justify='around', className='mb-1'),
dbc.Row([
dbc.Col(dbc.Label(['Choose Companies with mention count']), width=2),
dbc.Col(dcc.Dropdown(id = "input_item_dropdown", options = [], value=[], multi=True), width=10),
], justify='around', className='mb-1'),
# dbc.Row(dbc.Button(id="cancel_button_id", children="Cancel Running Job!")),
dbc.Row([
dbc.Col(html.Div(id="output_text", children=[]), width={'size':10, 'offset':2}),
], justify='around', className='py-3'),
dbc.Row([
html.Progress(id="progress_bar"),
]),
dbc.Row([
dbc.Col(dcc.Graph(id='output_graph', figure={}), width=12),
], justify='around', className='py-5'),
dcc.Store(id='stored-dataframe')
])
#app.long_callback(
[Output(component_id='output_text', component_property='children'),
Output(component_id="input_item_dropdown", component_property="options"),
Output(component_id='stored-dataframe', component_property='data'),
],
[Input(component_id="input_date_picker_range", component_property="start_date"),
Input(component_id="input_date_picker_range", component_property="end_date"),
],
manager=long_callback_manager,
running=[
(Output("output_text", "disabled"), False, True),
(
Output("output_graph", "style"),
{"visibility": "hidden"},
{"visibility": "visible"},
),
(
Output("progress_bar", "style"),
{"visibility": "visible"},
{"visibility": "hidden"},
),
],
)
def update_figure(start_date, end_date):
print(start_date)
print(end_date)
# Data Acquisition
TOP_N = 20
unique_org_list, top_companys, org_gp_pdf = get_ORG_info(get_daterange_entity_dataframe(start_date,end_date), TOP_N)
# For the div
# _text = str(f"Between {start_date} to {end_date} for all the organizations : { ', '.join (item_list_value) }")
_text = str(f"Between {start_date} to {end_date} there are {len(unique_org_list)} organizations mentioned in media.")
# Store the data in browser storage.
datasets = {
'so_1': org_gp_pdf.to_json(orient='split', date_format='iso'),
'so_2': top_companys,
}
return [_text], [{'label': str(c[0]) + f" ({c[1]})", 'value': str(c[0])} for c in unique_org_list[0:]], json.dumps(datasets)
#app.callback(
[Output(component_id='output_graph', component_property='figure')],
[Input(component_id="input_item_dropdown", component_property="value"),
Input(component_id='stored-dataframe', component_property='data')
],
progress=[Output("progress_bar", "value"), Output("progress_bar", "max")],
)
def update_graph_2(item_list_value, jsonified_cleaned_data):
# Load the stored DF and List from Browser storage
datasets = json.loads(jsonified_cleaned_data)
df_2 = pd.read_json(datasets['so_1'], orient='split')
top_companys = datasets['so_2']
if len(item_list_value) == 0:
fig = px.bar( df_2[df_2.ORG.isin(top_companys)].sort_values(['NEWS_DATE'], ascending=True), title=f"Showing top {len(top_companys)} organizations", x="NEWS_DATE", y="COUNT", color="ORG", barmode="group") # .query("ORG=='Mentice' | ORG=='Isofol Medical AB'")
else:
queryString = " | ".join([f"ORG=='{item}'" for item in item_list_value])
fig = px.bar(df_2.query(queryString).sort_values(['NEWS_DATE'], ascending=True) ,title=f"Showing some selected organizations", x="NEWS_DATE", y="COUNT", color="ORG", barmode="group") # .query("ORG=='Mentice' | ORG=='Isofol Medical AB'")
# align title
fig.update_layout(title_x=0.5, xaxis=dict(title_text='NEWS PUBLISH DATE'), yaxis=dict(title_text='DAILY ORG MENTION COUNT '))
return [fig]
if _name_ == "__main__":
app.run_server(port=8050, debug=False)
But When i am trying run the same application in multipage structure it is showing me #long_callback is not callable.
In Multipage structure my main App file is given below
app.py
from pages import topx_org, topx_per
import dash
from dash import html, dcc
from dash.long_callback import DiskcacheLongCallbackManager
from dash.dependencies import Input, Output
import dash_bootstrap_components as dbc
## Diskcache
import diskcache
cache = diskcache.Cache("./cache")
long_callback_manager = DiskcacheLongCallbackManager(cache)
app = dash.Dash(__name__,
suppress_callback_exceptions=True,
long_callback_manager=long_callback_manager,
external_stylesheets=[dbc.themes.BOOTSTRAP],
meta_tags=[{'name': 'viewport', 'content': 'initial-scale=1'}])
server = app.server
app.layout = html.Div([
dcc.Location(id='url', refresh=False),
html.Div(id='page-content')
])
#app.callback(Output('page-content', 'children'),
Input('url', 'pathname'))
def display_page(pathname):
if pathname == '/topx_org':
return topx_org.layout
elif pathname == '/topx_per':
return topx_per.layout
else:
return '404'
if _name_ == '__main__':
app.run_server(debug=True)
and the topx_org.py is given below
from dash import callback, long_callback
import json
from dash import html, dcc
from dash.dependencies import Input, Output
import dash_bootstrap_components as dbc
import datetime
import pandas as pd
import plotly.express as px
from query_4_entity_explr import get_ORG_info, get_daterange_entity_dataframe
today = datetime.datetime.today().date()
date_30_day_back = (datetime.datetime.today() - datetime.timedelta(days=1)).date()
layout = dbc.Container([
dbc.Row([
dbc.Col(html.H3("Explore Organizations mentioned in media", className='text-center text-primary py-5'), width=12)
]),
dbc.Row([
dbc.Col(dbc.Label(['Select daterange' ]), width={'size':2, 'offset':0}),
dbc.Col(dcc.DatePickerRange(id='input_date_picker_range', display_format='YYYY-MM-DD',start_date=date_30_day_back, end_date=today), width={'size':10, 'offset':0}),
], justify='around', className='mb-1'),
dbc.Row([
dbc.Col(dbc.Label(['Choose Companies with mention count']), width=2),
dbc.Col(dcc.Dropdown(id = "input_item_dropdown", options = [], value=[], multi=True), width=10),
], justify='around', className='mb-1'),
dbc.Row([
dbc.Col(html.Div(id="output_text", children=[]), width={'size':10, 'offset':2}),
], justify='around', className='py-3'),
dbc.Row([
dbc.Col(dcc.Graph(id='output_graph', figure={}), width=12),
], justify='around', className='py-5'),
dcc.Store(id='stored-dataframe')
])
# Output(component_id='output_graph', component_property='figure'),
#callback(
[Output(component_id='output_text', component_property='children'),
Output(component_id="input_item_dropdown", component_property="options"),
Output(component_id='stored-dataframe', component_property='data'),
],
[Input(component_id="input_date_picker_range", component_property="start_date"),
Input(component_id="input_date_picker_range", component_property="end_date"),
],
progress=[Output("progress_bar", "value"), Output("progress_bar", "max")],
)
def update_figure(start_date, end_date):
print(start_date)
print(end_date)
# print(item_list_value)
# Data Acquisition
TOP_N = 20
unique_org_list, top_companys, org_gp_pdf = get_ORG_info(get_daterange_entity_dataframe(start_date,end_date), TOP_N)
# For the div
# _text = str(f"Between {start_date} to {end_date} for all the organizations : { ', '.join (item_list_value) }")
_text = str(f"Between {start_date} to {end_date} there are {len(unique_org_list)} organizations mentioned in media.")
# Store the data in browser storage.
datasets = {
'so_1': org_gp_pdf.to_json(orient='split', date_format='iso'),
'so_2': top_companys,
}
return [_text], [{'label': str(c[0]) + f" ({c[1]})", 'value': str(c[0])} for c in unique_org_list[0:]], json.dumps(datasets)
#long_callback(
[Output(component_id='output_graph', component_property='figure')],
[Input(component_id="input_item_dropdown", component_property="value"),
Input(component_id='stored-dataframe', component_property='data')
],
running=[
(Output("output_text", "disabled"), False, True),
(
Output("output_graph", "style"),
{"visibility": "hidden"},
{"visibility": "visible"},
),
(
Output("progress_bar", "style"),
{"visibility": "visible"},
{"visibility": "hidden"},
),
],
)
def update_graph_2(item_list_value, jsonified_cleaned_data):
# Load the stored DF and List from Browser storage
datasets = json.loads(jsonified_cleaned_data)
df_2 = pd.read_json(datasets['so_1'], orient='split')
top_companys = datasets['so_2']
if len(item_list_value) == 0:
fig = px.bar( df_2[df_2.ORG.isin(top_companys)].sort_values(['NEWS_DATE'], ascending=True), title=f"Showing top {len(top_companys)} organizations", x="NEWS_DATE", y="COUNT", color="ORG", barmode="group") # .query("ORG=='Mentice' | ORG=='Isofol Medical AB'")
else:
queryString = " | ".join([f"ORG=='{item}'" for item in item_list_value])
fig = px.bar(df_2.query(queryString).sort_values(['NEWS_DATE'], ascending=True) ,title=f"Showing some selected organizations", x="NEWS_DATE", y="COUNT", color="ORG", barmode="group") # .query("ORG=='Mentice' | ORG=='Isofol Medical AB'")
# align title
fig.update_layout(title_x=0.5, xaxis=dict(title_text='NEWS PUBLISH DATE'), yaxis=dict(title_text='DAILY ORG MENTION COUNT '))
return [fig]
I am having the following error
#long_callback(
TypeError: 'module' object is not callable
(Updated) According to this post, this is not possible yet because long_callback requires the app object (#app.long_callback). If you try to import the app object in your page file, you will create a circular import which will cause an error.
The only possibility mentionned in the post is to put all the long callbacks in the app.py file. The 'normal' callbacks and the layout can stay in the pages files.
This is now possible in the latest dash version by using the function app = dash.get_app() and then calling #app.long_callback.

How to show completion percentage in a bootstrap card in python dash?

I am building a dash application and have calculated a completion_percentage for the project completion. I am using dash_bootstrap_components and want to show that percentage inside the card. Is there any way to do so or is there any other way to graphically show the completion percentage on the application page?
Below is the code which I am using as part of the layout
completion_percentage = str((closed_tickets / total_tickets) * 100)
app.layout = html.Div(
children=[
html.H1(children="Project Analytics",),
html.P(
children="Get the status!",
),
dcc.Graph(
figure=fig,
),
dcc.Graph(
figure=pie_chart
),
dbc.Card(
dbc.CardBody(
[
html.H4("Completion Percentage", className="card-title"),
dbc.CardText(completion_percentage)
]
)
)
]
)
The above is giving me error as cardtext excpets P or Div. Can someone help with the following.
As the error says:
AttributeError: CardText has been removed from dash-bootstrap-components. Set className='card-text' on a html component such as Div, or P instead. CardText originally used P.
So you can use html.P or html.Div where you're now using dbc.CardText.
Example:
from dash import Dash
import dash_html_components as html
import dash_bootstrap_components as dbc
closed_tickets = 10
total_tickets = 80
completion_percentage = str((closed_tickets / total_tickets) * 100)
app = Dash(
external_stylesheets=[dbc.themes.BOOTSTRAP]
)
app.layout = html.Div(
children=[
html.H1(children="Project Analytics",),
html.P(
children="Get the status!",
),
dbc.Card(
dbc.CardBody(
[
html.H4("Completion Percentage", className="card-title"),
html.P(completion_percentage)
]
)
)
]
)
if __name__ == "__main__":
app.run_server()
https://dash-bootstrap-components.opensource.faculty.ai/docs/components/card/

How can I have multiple Navigations for the same URL paths in Dash

I am trying to add multiple navigations for the same URL path.
my code..
import dash
import dash_core_components as dcc
import dash_html_components as html
import dash_bootstrap_components as dbc
import dash_table
app = dash.Dash()
index_layout = html.Div([
# represents the URL bar, doesn't render anything
dcc.Location(id='url', refresh=False),
html.Br(),
dcc.Link(dbc.Button('Page1',
color="secondary",
className="mr-1",
outline=True,
style={"width":400,
"vertical-align": "middle",
}
), href='/page1'),
html.Br(),html.Br(),html.Br(),html.Br(),html.Br(),
dcc.Link(dbc.Button("Page2",
style={"width":400,
"vertical-align": "middle"},
color="secondary",
className="mr-1",
outline=True
), href='/page2'),
])
page1_layout = html.H1("Page1")
page2_layout = html.H1("Page2")
app.layout = html.Div([
dcc.Location(id='url-nav', refresh=True),
html.Span(dbc.Nav(
[
dbc.NavLink(dbc.NavLink("Page1", href="/page1")),
dbc.NavLink(dbc.NavLink("Page2", href="/page2")),
],
pills=True,),
className="ml-auto"
),
dcc.Location(id='url', refresh=True),
html.Center([
html.H3('DEMO AP',id='title'),
# content will be rendered in this element
html.Div(id='page-content'),
],),
])
### CALLBACKS
#app.callback(dash.dependencies.Output('page-content', 'children'),
[dash.dependencies.Input('url', 'pathname')])
def display_page(pathname="/"):
ctx = dash.callback_context
triggered_by = ctx.triggered[0].get("prop_id")
if pathname == "/page1":
return page1_layout
elif pathname == "/page2":
return page2_layout
else:
return index_layout
if __name__ == "__main__":
app.run_server()
Button navigations are working fine, but html.Nav only works on the very first click, not consistent and not working on the following clicks.
Kindly help.
From testing this out the problem seems to be with this line in index_layout:
dcc.Location(id='url', refresh=False),
If you look in the console you will see that a lot of requests are sent constantly when you're on the main page (when index_layout is rendered).
When this line is removed your code works as expected.
Working solution:
import dash
import dash_core_components as dcc
import dash_html_components as html
import dash_bootstrap_components as dbc
import dash_table
app = dash.Dash()
index_layout = html.Div(
[
html.Br(),
dcc.Link(
dbc.Button(
"Page1",
color="secondary",
className="mr-1",
outline=True,
style={
"width": 400,
"vertical-align": "middle",
},
),
href="/page1",
),
html.Br(),
html.Br(),
html.Br(),
html.Br(),
html.Br(),
dcc.Link(
dbc.Button(
"Page2",
style={"width": 400, "vertical-align": "middle"},
color="secondary",
className="mr-1",
outline=True,
),
href="/page2",
),
]
)
page1_layout = html.H1("Page1")
page2_layout = html.H1("Page2")
app.layout = html.Div(
[
dcc.Location(id="url-nav", refresh=True),
html.Span(
dbc.Nav(
[
dbc.NavLink(dbc.NavLink("Page1", href="/page1")),
dbc.NavLink(dbc.NavLink("Page2", href="/page2")),
],
pills=True,
),
className="ml-auto",
),
dcc.Location(id="url", refresh=True),
html.Center(
[
html.H3("DEMO AP", id="title"),
# content will be rendered in this element
html.Div(id="page-content"),
],
),
]
)
### CALLBACKS
#app.callback(
dash.dependencies.Output("page-content", "children"),
[dash.dependencies.Input("url", "pathname")],
)
def display_page(pathname="/"):
ctx = dash.callback_context
triggered_by = ctx.triggered[0].get("prop_id")
if pathname == "/page1":
return page1_layout
elif pathname == "/page2":
return page2_layout
else:
return index_layout
if __name__ == "__main__":
app.run_server()
The problem here I think is that there are two Location components rendered at the same time with the same id (url). This apparently causes the callback to be called constantly and causes inconsistent link behavior.

Categories

Resources