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

Hi,

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...
    fig1.add_trace(go.Scatter(x=trace_data['base'],
                             y=trace_data[trace],
                             mode='lines',
                             marker=dict(color=trace_colors[color_idx % len(trace_colors)]),
                             name=trace))
    fig1.add_trace(go.Scatter(x=[trace_data['base'].iloc[-1]],
                             y=[trace_data[trace].iloc[-1]],
                             mode='markers',
                             marker=dict(color=trace_colors[color_idx % len(trace_colors)]),
                             showlegend=False))
    color_idx += 1
fig1.show()
      html.Button("Refresh Graph", id="update-graph", style={'background-color': '#cf6e23','border-color': '#cf6e23'}),
      html.Button("Download CSV", id="btn-download-csv"),
      dcc.Download(id="download-csv")
      ]
   )

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

@app.callback(
    Output("download-csv", "data"),
    Input("btn-download-csv", "n_clicks"),
    State("fig1", "figure"),
    prevent_initial_call=True,
)
def func(n_clicks, figure):
   print(figure["data"])
   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})]

fig.show()

newplot (11)

print(visible_trace)

[Scatter({
    'visible': True, 'x': [1, 2, 3], 'y': [4, 5, 6]
})]
2 Likes

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?