Anurag Sharma
Anurag Sharma

Reputation: 76

Unable to use Dask dataframe with Plotly Dash

I am trying to use Dask to read a CSV file and plot it using Plotly Dash. While doing that I am getting following error:

dash.exceptions.InvalidCallbackReturnValue: The callback for property `figure` of component `graph`
returned a value which is not JSON serializable.

In general, Dash properties can only be dash components, strings,
dictionaries, numbers, None, or lists of those.

Below is my code for reference:

@dashapp.callback(
    Output('graph', 'figure'),
    [Input('dropdown', 'value')])
    def update_graph(dropdown_value):
        data = dd.read_csv('data/output.csv')
        
        return {
            'layout': {
                'title': 'Graph of {}'.format(dropdown_value),
                'margin': {
                    'l': 20,
                    'b': 20,
                    'r': 10,
                    't': 60
                }
            },
            'data': [{'x': data['col1'].values, 'y': data['col2'].values}]
        }

Upvotes: 0

Views: 978

Answers (1)

bas
bas

Reputation: 15722

You need to call compute() on data before you pass it to the graph dictionary.

When you do this:

data = dd.read_csv('data/output.csv')

the type of data is <class 'dask.dataframe.core.DataFrame'>.

Dash doesn't know what a Dask Dataframe is. So you need to call compute so you get a Pandas dataframe that you can get the column values from as a list:

@dashapp.callback(Output("graph", "figure"), [Input("dropdown", "children")])
def update_graph(dropdown_value):
    data = dd.read_csv("data/output.csv").compute()

    return {
        "layout": {
            "title": "Graph of {}".format(dropdown_value),
            "margin": {"l": 20, "b": 20, "r": 10, "t": 60},
        },
        "data": [{"x": data["col1"].values, "y": data["col2"].values}],
    }

Upvotes: 1

Related Questions