Delete trace by name from plotly.graph_object

Delete trace by name from plotly.graph_object - Is this possible? The only way that I can think of, would be to overwrite fig['data'] with itself minus the track to delete, which seems quite clumsy

found a way:
the callback needs to have a State('figure', 'figure') β†’ fig_state
then one can use:

for i, trace in enumerate(fig_state['data']):
   if 'name' in trace and trace['name'] == 'name_to_be_deleted':
      patched_fig['data'][i].clear()

hello, I found there is a more thorough way to do it.
Just change your last statement into:

patched_fig[β€˜data’].remove(fig_state[β€˜data’][i])

.clear() can only clear the content in the item (which is a dict), but left the {} behind.
It might look right in the figure, but the empty curly brackets will still take up a place in [β€˜data’] list.

This improvement might be trivial, but I found it helps me somehow while I am trying to develop functions to add and remove traces dynamically.

1 Like