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.
Related
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)
In my dash I have a callback that create a pd.to_dict object that is stored with dcc.Store, in order to be used for further plots.
I am trying to create a download button to download this created data frame.
This is part of my code (removed other import or layout options) :
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State
app = dash.Dash(__name__)
app.layout = html.Div([
html.H2('Enter a text query'),
dcc.Store(id='memory'),
html.Button('Submit', id='button', n_clicks=0),
html.Button("Download CSV", id="csv"),
dcc.Download(id="download-df")])
#app.callback(
Output('memory', 'data'),
[Input('button', 'n_clicks')],
[State('searchterm', 'value')]
)
def create_df_func(n_clicks, searchterm):
#some code to create df
return df.to_dict(orient='records')
#app.callback(
Output('download-df', 'data'),
[Input('csv', 'n_clicks')],
[State('memory', 'data')],
prevent_initial_call=True,
)
def download_csv(n_clicks, df):
data = pd.DataFrame(df)
return dcc.send_data_frame(data.to_csv, "mydf.csv")
if __name__ == '__main__':
app.run_server(debug=True)
But when running the app.py, I get 'dash_core_components' has no attribute 'send dataframe', even though it has it.
I have dash version 2.0.0.
I have dash version 2.0.0
Replace how you import dash core components from this
import dash_core_components as dcc
to this
from dash import dcc
As of Dash 2, the development of dash-core-components has been moved to the main Dash repo
quote source
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
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)
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.