Double-click legend to isolate traces and then download selected data in a csv


I’m plotting a figure that includes some traces. So far I have been able to download the content of the figure. I am also able to double click on the legend and isolate specific traces but when I click on the download button the content of all traces is included in the exported csv, instead of only the content of the selected traces.

As an example I use the following code:

trace_data = pd.DataFrame({'base': [0, 1, 2, 3, 4],
                           'trace1': [1, 2, 3, 4, 5],
                           'trace2': [1.5, 1.9, 2, 3.9, 6],
                           'trace3': [2, 1, 3.3, 4.4, 4.5],
                           'trace4': [0, 3, 2, 1, 3]})

trace_colors = plotly.colors.qualitative.D3
color_idx = 0

fig1 = go.Figure()
for trace in ['trace1', 'trace2', 'trace3', 'trace4']:
    # Perform a lot of data wrangling in Pandas here...
                             marker=dict(color=trace_colors[color_idx % len(trace_colors)]),
                             marker=dict(color=trace_colors[color_idx % len(trace_colors)]),
    color_idx += 1
      html.Button("Refresh Graph", id="update-graph", style={'background-color': '#cf6e23','border-color': '#cf6e23'}),
      html.Button("Download CSV", id="btn-download-csv"),

      Output("fig1", "figure"), 
      Input("update-graph", "n_clicks"))
def callback_fig1(n_clicks):
   fig1 = make_graph()
   return fig1

    Output("download-csv", "data"),
    Input("btn-download-csv", "n_clicks"),
    State("fig1", "figure"),
def func(n_clicks, figure):
   return dcc.send_data_frame(figure["data"].to_csv, "my_csv.csv")

if __name__ == '__main__':
   app.run_server(debug=True, port='5000')

How can I download only the content of the selected traces?

Thank you in advance!

HI @dash_newb welcome to the forums.

I think by double clicking a trace in the legend you are actually not selecting anything, you are just changing the visibility of the corresponding trace in the figure.

You could check for the visible state of the trace and export only the visible traces. Here is something related to that:

An example:

import plotly.graph_objects as go

# create figure
fig = go.Figure()

# add traces
fig.add_trace(go.Scatter(x=[1,2,3], y=[1,2,3], visible='legendonly'))
fig.add_trace(go.Scatter(x=[1,2,3], y=[4,5,6], visible=True))

# extract only visible traces
visible_trace = [trace for trace in fig.select_traces(selector={'visible':True})]

newplot (11)


    'visible': True, 'x': [1, 2, 3], 'y': [4, 5, 6]
1 Like

Great - thanks! Now by filtering based on the 'visibility' parameter I am able to export only the visible traces.

1 Like

@AIMPED Right now I am able to download in a CSV the content of the whole time series that is on the x-axis. However, I would like to be able to download only a slice of it, so only the data from the period that I have zoomed in.
Would that be possible?