Plotly Dash Dropdown Menu Invalid Argument Error - python

I am trying to create a basic Dash app in a Jupyter notebook with JupyterDash. The dropdown menu is displaying the below error message when I run the script.
Below is the code I am using. I am not sure what I am doing wrong here. Any help would be greatly appreciated.
# import the libraries
from pathlib import Path
import plotly.express as px
import dash
from dash import Dash, dcc, html
from dash.dependencies import Input, Output, State
import pandas as pd
import dash_bootstrap_components as dbc
from jupyter_dash import JupyterDash
# Load the Dataframe
df = pd.read_csv(Path("./ds_salaries.csv"))
# Preview the dataset
df.head()
# Create the dash app
app = JupyterDash(__name__)
# Bar chart employee residence
fig = px.histogram(df, x="employee_residence")
# Set up the app layout - dropdown for job title
app.layout = html.Div(children=[
html.H1('Data Science Job Analyzer', style={'textAlign':'center'}),
html.Br(),
dcc.Dropdown(
id='job-dropdown',
options=df["job_title"].unique(),
style={"width": "50%", "offset":1,},
clearable=False
),
dcc.Graph(id='hist', figure=fig)
])
# Run local server
if __name__ == '__main__':
app.run_server(debug=True)

Related

JupyterDash in JupyterLabs fails after using plotly express in a prior cell

I have a notebook in which I want to display some interactive figures using plotly, then construct a dashboard within the notebook using JupyterDash. The following code works fine on my machine:
import numpy as np
import pandas as pd
import plotly.graph_objects as go
import plotly.express as px
df = pd.DataFrame({'category':['a','b','c'],
'value':[1,2,3]})
px.bar(df, x='category', y='value')
import dash
from jupyter_dash import JupyterDash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = JupyterDash(__name__, external_stylesheets=external_stylesheets)
app.layout = html.Div(
[
html.H1("Test dashboard")
]
)
if __name__ == '__main__':
app.run_server(mode='inline', debug=True, port=8060)
However, when I split this code across two cells, as follows:
Cell 1
import numpy as np
import pandas as pd
import plotly.graph_objects as go
import plotly.express as px
df = pd.DataFrame({'category':['a','b','c'],
'value':[1,2,3]})
px.bar(df, x='category', y='value')
Cell 2
import dash
from jupyter_dash import JupyterDash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = JupyterDash(__name__, external_stylesheets=external_stylesheets)
app.layout = html.Div(
[
html.H1("Test dashboard")
]
)
if __name__ == '__main__':
app.run_server(mode='inline', debug=True, port=8060)
Then I receive the following error:
AttributeError: module 'google.colab.output' has no attribute 'serve_kernel_port_as_iframe'
The only thing that is different between the two scenarios is that in the second the code is split into two cells. However, in scenario 2, the dashboard displays normally if I comment out the call to px.bar in the first cell.
What I've tried:
Many different port numbers
Updating various packages to the latest versions, including plotly, dash, JupyterDash, and google.colab
Much appreciation for any insight you can provide
Solved by downgrading JupyterDash to a version that predates the functionality to operate on Google Colab, which was causing the issue:
pip install jupyter-dash==0.2.1

Dash live-update with Postgresql, SQLAlchemy and Pandas not updating

I am new to Dash plotly and I am trying to use the Live-Update of Dash framework to get data from PostgreSQL every 5 seconds. The web application runs smoothly, but I need to refresh the web to update the graph. I am new to dash and really need help regarding this one.
from sqlalchemy.sql import select
from sqlalchemy import create_engine
import dash
import pandas as pd
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Output, Input
import plotly
import plotly.express as px
import plotly.graph_objs as go
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
app.layout = html.Div([
dcc.Graph(id='live-graph', animate=True),
dcc.Interval(
id='graph-update',
interval=200,
n_intervals=0
)
])
#app.callback(Output('live-graph', 'figure'),
Input('graph-update', 'n_intervals'))
def update_graph(n):
engine = create_engine('postgresql+psycopg2://username:password#127.0.0.1:5432/Cryptocurrency')
with engine.connect() as conn:
df = pd.read_sql("select * from \"cryptocurrency\"", conn)
fig = px.line(df, x="time", y="bitcoin_php")
return fig
if __name__ == '__main__':
app.run_server(debug=True)
I just updated the code above. I used context manager and reduced the interval to 200.

Plotly: How to rewrite a standard dash app to launch it in JupyterLab?

You can find a bunch of Dash examples in the plotly docs, and most examples end with a note on how to build figures using Dash:
What About Dash? Dash is an open-source framework for building
analytical applications, with no Javascript required, and it is
tightly integrated with the Plotly graphing library.
Learn about how to install Dash at https://dash.plot.ly/installation.
But I'd like to fire them up in JupyterLab instead. So what changes would I have to make in the following 'normal' Dash app to make it run in JupyterLab?
Code sample:
import plotly.graph_objects as go
import plotly.express as px
import dash
import dash_core_components as dcc
import dash_html_components as html
# data and plotly figure
df = px.data.gapminder().query("country=='Canada'")
fig = px.line(df, x="year", y="lifeExp", title='Life expectancy in Canada')
# Set up Dash app
app = dash.Dash()
app.layout = html.Div([
dcc.Graph(figure=fig)
])
# Launch Dash app
app.run_server(debug=True,
use_reloader=False # Turn off reloader if inside Jupyter
)
Any working Dash app can be launched from JupyterLab with the setup described in the question by specifying use_reloader=False in:
app.run_server(debug=True,
use_reloader=False # Turn off reloader if inside Jupyter
)
But if you'd like to use JupyterLab and select between launching the app in your default browser, inline in a cell or directly in Jupyter in its own tab, just follow these simple steps:
Change the following lines
# 1
import dash
# 2
app = dash.Dash()
# 3
app.run_server(debug=True,
use_reloader=False # Turn off reloader if inside Jupyter
)
To this:
# 1
from jupyter_dash import JupyterDash
# 2
app = JupyterDash(__name__)
# 3
app.run_server(mode='inline', port = 8070, dev_tools_ui=True,
dev_tools_hot_reload =True, threaded=True)
This will launch Dash inline directly in JupyterLab:
But you can also go for mode='external' to launch Dash it its own tab:
And you can set mode='external' to launch it in your default browser.
Complete code with changes:'
import plotly.graph_objects as go
import plotly.express as px
# import dash
from jupyter_dash import JupyterDash
import dash_core_components as dcc
import dash_html_components as html
# data and plotly figure
df = px.data.gapminder().query("country=='Canada'")
fig = px.line(df, x="year", y="lifeExp", title='Life expectancy in Canada')
# Set up Dash app
# app = dash.Dash()
app = JupyterDash(__name__)
app.layout = html.Div([
dcc.Graph(figure=fig)
])
# Launch Dash app
# app.run_server(debug=True,
# use_reloader=False # Turn off reloader if inside Jupyter
# )
app.run_server(mode='inline', port = 8070, dev_tools_ui=True,
dev_tools_hot_reload =True, threaded=True)

Python plotly dash - button to link to webpage

I am using python dash and I'd like to have a button below my table that when clicked, will take the user to a specific webpage. I am very - VERY - new to using dash so I'm not even sure if this functionality exists. I did search this topic specifically to python dash and came up empty handed. Any and all help is appreciated, thank you!
You can use dash_bootstrap_components or dbc to do that. Check this page for more detailed information about dbc: https://dash-bootstrap-components.opensource.faculty.ai/docs/components/button/
To summarize, what you need to do:
If you haven't done yet, pip install dbc:
pip install dash-bootstrap-components
Import it to your code:
import dash_bootstrap_components as dbc
Configure your app with one of the dbc themes. When you creat the app, just include an external_stylesheet:
app = Dash(external_stylesheets=[dbc.themes.CYBORG])
Include the dbc.Button componen in your app (see examples in documentation or below).
Here is an example:
from dash import Dash, html
import dash_bootstrap_components as dbc
app = Dash(external_stylesheets=[dbc.themes.CYBORG])
app.layout = html.Div([
html.Div("Default format"),
dbc.Button(
children='Open Page',
id='button_plain',
href = "https://stackoverflow.com/"),
html.Br(),
html.Br(),
html.Br(),
html.Div("Modify format"),
dbc.Button(
children='Open Page',
id='button_format',
color = "primary",
outline = True, #more lightweight format
size = "lg", #sm, lg
href = "https://stackoverflow.com/"),
])
if __name__ == '__main__':
app.run_server(debug=True)
More about dbc Themes: https://bootswatch.com/
use this for button example and to learn more please use this
link:https://dash.plotly.com/dash-core-components.
import dash
import dash_html_components as html
import dash_core_components as dcc
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
app.layout = html.Div([
html.Div(dcc.Input(id='input-box', type='text')),
html.Button('Submit', id='button'),
html.Div(id='output-container-button',
children='Enter a value and press submit')
])
#app.callback(
dash.dependencies.Output('output-container-button', 'children'),
[dash.dependencies.Input('button', 'n_clicks')],
[dash.dependencies.State('input-box', 'value')])
def update_output(n_clicks, value):
return 'The input value was "{}" and the button has been clicked {} times'.format(
value,
n_clicks
)
if __name__ == '__main__':
app.run_server(debug=True)

display datatable after filtering rows from dropdown list in dash

I'm new to Dash. I would like to make a app, where I can select values from dropdown filter, filter dataset and display the data table. I'm using dash_table.
My example app code is below. No datatable is shown. Does anyone know what I did wrong? How can I render dash table in dash app?
import dash
import dash_html_components as html
import dash_core_components as dcc
import dash_table as dt
from dash.dependencies import Input, Output
import pandas as pd
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/solar.csv')
app = dash.Dash(__name__)
states = df.State.unique().tolist()
app.layout = html.Div(
children=[
dcc.Dropdown(
id='filter_dropdown',
options=[{'label':st, 'value':st} for st in states],
value = states[0]
),
dt.DataTable(id='table-container') ]
)
#app.callback(
Output('table-container', 'data'),
[Input('filter_dropdown', 'value') ] )
def display_table(state):
dff = df[df.State==state]
return dff
if __name__ == '__main__':
app.run_server(debug=True)
BTW, do anyone know where I can find collections of dash app gallery with code?
You have to set the columns of your data table and return your dataframe as a dict in a special form. So change these two lines in your code to make it work.
dt.DataTable(id='table-container', columns=[{'id': c, 'name': c} for c in df.columns.values])
return dff.to_dict('records')
BTW, do anyone know where I can find collections of dash app gallery with code?
Best place with lots of examples with code is the Dash User Guide. You can for instance find the data table there.

Categories