DEV Community

Wesley Cheek
Wesley Cheek

Posted on

Storing your data in a Plotly Dash data dashboard

Plotly Dash is a great framework for developing interactive data dashboards using Python, R, and Javascript. It works alongside 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 component. 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 TimeDeltas and DateTime data types to a str or float.
2) You will lose your index information in the data conversation, so be sure to pd.DataFrame.reset_index() before you store your DataFrame

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(
Enter fullscreen mode Exit fullscreen mode

Store a Pandas DataFrame using dcc.Store

Now to store the dataframe, you can use the pd.DataFrame.to_json() method, after resetting its index.

    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")]
Enter fullscreen mode Exit fullscreen mode

Access a Pandas DataFrame stored in dcc.Store

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.

    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]
Enter fullscreen mode Exit fullscreen mode

dcc.Store is a great way to centralize data processing and allow data to be accessed across your app.

Top comments (1)

nightbird07 profile image

have you considered the problem of converting from joson to data frame and vise versa is quite expensive