How to target a specific trace in pie chart by name when using update_traces() selector attribute?

Question:

The idea is to change the hover template only in the "Resto" trace. Here is a reproducible example:

df_stack = pd.DataFrame({"Country": ['Brasil','China','Estados unidos','Chile','India','Paises bajos','Vietnam','Peru','Corea, republica de','Indonesia','Resto'],
              "Dolars": [11599.42961799,7671.6791054099995,6198.81430321,4578.07,4153.13352132,3352.11349841,2998.44092833,2247.29957849,1968.7549113200002,1890.7284090800001,35635.107780379985],
              "Pct_change":[0.0846110761489467,0.2953716769009316,0.41561413372310074,0.21787800280514857,0.09245460739576772,0.18325289020293622,0.023857445957433443,0.2555960957383905,0.2319776811635097,0.12068329801455069,0.0]
              })


fig = go.Figure(data=[go.Pie(labels=df_stack["Country"], values=df_stack['Dolars'], hole=.5,
                customdata = np.transpose([df_stack["Pct_change"],
                                            ]),
                hovertemplate="<b>%{label}</b> <br>Dolars: $%{value:,.2f}"
    "<br>Percent: %{percent:.1%}"
    "<br>Pct_change: %{customdata[0]:.1%}"
    "<br<extra></extra>>",
                )])

fig.update_layout(title_text = f"Change hover of specific trace in pie chart", template = None, font_family = "verdana",
                margin = dict(t=70, l=10, r=10, b=30), separators = ",.",
                showlegend= False,)
fig.update_traces(hovertemplate=None, selector=dict(name = 'Resto')) #It won't work!!!

Unlike with Scatter traces, the last line of code won’t do the trick.

fig.update_traces(hovertemplate=None, selector=dict(name = 'Resto')) #It won't work!!!

enter image description here
Help is much appreciated!

Asked By: Keynes is not dead

||

Answers:

r-beginners is right, and I would like to add a few details that I hope will be of interest.

Generally, unique hovertemplates can only be applied to specific traces. So as long as you’ve got different traces within a figure object, you can apply any hovertemplate you would like to each trace. Unfortunately, a Plotly pie chart consists of only one trace, even though it might not look like that since you’ve got different colors in the pie chart.

There are a few details in your code that reveal how these things are tied together. When you construct a pie chart with go.Figure(go.Pie()), you’re creating one figure object containing one trace.

And if you take a look at the structure of your pie chart with fig.data, you’ll see how hovertemplate is associated with the only trace there:

(Pie({
     'customdata': array([[0.08461108],
                          [0.29537168],
                          [0.41561413],
                          [0.217878  ],
                          [0.09245461],
                          [0.18325289],
                          [0.02385745],
                          [0.2555961 ],
                          [0.23197768],
                          [0.1206833 ],
                          [0.        ]]),
     'hole': 0.5,
     'hovertemplate': ('<b>%{label}</b> <br>Dolars: $%' ... 'ata[0]:.1%}<br<extra></extra>>'),
     'labels': array(['Brasil', 'China', 'Estados unidos', 'Chile', 'India', 'Paises bajos',
                      'Vietnam', 'Peru', 'Corea, republica de', 'Indonesia', 'Resto'],
                     dtype=object),
     'values': array([11599.42961799,  7671.67910541,  6198.81430321,  4578.07      ,
                       4153.13352132,  3352.11349841,  2998.44092833,  2247.29957849,
                       1968.75491132,  1890.72840908, 35635.10778038])
 }),)

And what fig.update_traces(selector=... would potentially do for you is apply your desired hovertemplate to a trace within a figure object. If you were to try to construct a pie chart with multiple traces with fig.add_trace like this:

import plotly.graph_objects as go
fig = go.Figure()
fig.add_trace(go.Pie(values = [1,2,3]))
fig.add_trace(go.Pie(values = [5,6,7]))

Then each fig.add_trace would only overwrite the single existing trace in your figure object, so there’s not much help there either.

I hope this clarifies things a bit, and that you are able to find other methods to convey the information in your visualization.

Answered By: vestland