Saving the data from plotly graph into csv or excel file

Viewed 525

I have a pandas dataframe with 1 datetime column date, 2 category type columns cat_1 and cat_2, and a count column ct. Each number in the ct column corresponds to count of items that fall into corresponding values of both cat_1 & cat_2 columns generated on that particular date. Using plotly-Dash, I was able to create a webpage on local system where I can chose multiple combinations of cat_1 and cat_2 and able to view date v/s count_for_chosen_combo plot, where count_for_chosen_combo is the items generated for chosen combination of cat_1 and cat_2 on that particular date. Now I want to know if I can download the data for the chosen combination for which is represented bye the plot into csv or xlsx or any other formats with the click of mouse rather than doing it manually?

1 Answers

What you need is:

  1. Callback that accepts the click event of download link/button. As an Input argument here you can accept all the filters. ie. dropdown list value
@app.callback(Output('my-link', 'href'), [Input('my-dropdown', 'value')])
def update_link(value):
    return '/dash/urlToDownload?value={}'.format(value)
  1. A flask route that will create a dataframe and sends it to machine using flask.send_file
@app.server.route('/dash/urlToDownload') 
def download_csv():
    value = flask.request.args.get('value')
    # use value to perform filter on your df
    # now send the df using `send_file`.
    return send_file(your_df,
                     mimetype='text/csv',
                     attachment_filename='downloadFile.csv',
                     as_attachment=True)
Related