Skip to content Skip to sidebar Skip to footer

How To Apply A Counter Or Otherwise Index Elements Using A Lambda Function?

Similar questions have been asked here and here, but I can't get it to work for my particular use case which is the for_each_trace functionality for Plotly that can be used like th

Solution 1:

If you want to combine the counter and the update method together, rather than using a lambda I might do something like:

deftrace_name_updater():
    counter = itertools.count(start=1)
    defupdate_trace_name(t):
        t.update(name=f'line {next(counter)}')

    return update_trace_name

and use it like:

fig.for_each_trace(trace_name_updater())

In this case the counter will live in the closure of the returned update_trace_name function.

Calling trace_name_updater() again will give a new counter.

My question is still why you need to do this at all if you can set the trace names upon their initialization, but maybe there is a reason that wasn't explained in your question.

Post a Comment for "How To Apply A Counter Or Otherwise Index Elements Using A Lambda Function?"