Plotly to bring your beautiful visualizations to the masses.
One problem that is oftentimes encountered when developing
Dash apps is being able to pass data around your app. Luckily, this is easy to do for small datasets using the
dcc.Store stores your data as a
JSON object inside a user's browser.
The most common library for working with data in a data scientist's tool kit is
pandas, so how can we store a
pandas DataFrame in our dash app? It's easy, but there are some things to keep in mind.
1) 'special' data types aren't going to be
JSON serializable. You need to convert your
DateTime data types to a
2) You will lose your
index information in the data conversation, so be sure to
pd.DataFrame.reset_index() before you store your
Create the data store in your app
dcc.Store can be placed anywhere in your app's layout.
from dash import dcc def layout(): return html.Div( [ dcc.Store(id="current-data"), dcc.Graph(id="graph") ] )
Pandas DataFrame using
Now to store the dataframe, you can use the
pd.DataFrame.to_json() method, after resetting its index.
@callback( output=[Output("current-data", "data")], ) def store_current_data(): # Some loading from file/remote and data processing return [data.reset_index().to_json(orient="split")]
Pandas DataFrame stored in
Now we can
pd.read_json() to retrieve the
DataFrame from the store in a different callback! Return a
Plotly Figure to a
dcc.Graph output to plot your data.
@callback( inputs=[Input("current-data", "data")], output=[Output("graph", "figure")] ) def retrieve_current_data_and_plot(data): df = pd.read_json(orient="split") # You can `set_index` here to get your original index back. # Create plotly figure here to display our data! fig = ... return [fig]
dcc.Store is a great way to centralize data processing and allow data to be accessed across your app.
Top comments (0)