如何使用update_traces()的selector按名称修改饼图特定trace的悬停模板?
问题
需要仅修改饼图中名为“Resto”的扇区的悬停模板(hovertemplate),但尝试使用fig.update_traces(hovertemplate=None, selector=dict(name='Resto'))时无法生效,可复现代码如下:
import pandas as pd import plotly.graph_objects as go import numpy as np 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!!!
解决方案
Pie图和Scatter图的核心结构不一样:Scatter可以把每个数据点做成单独trace,但Pie图的所有扇区都属于同一个trace,所以selector=dict(name='Resto')根本找不到目标——因为“Resto”只是trace里的一个label,不是单独的trace名称。
下面提供两种可行的解决方法:
方法1:用hovertext自定义单个扇区的悬停内容(推荐)
给每个扇区生成对应的悬停文本,其中单独给“Resto”设置特殊内容,然后在hovertemplate里直接引用这个文本即可:
import pandas as pd import plotly.graph_objects as go import numpy as np 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] }) # 逐个生成悬停文本,给Resto单独定制 hover_texts = [] total_dolars = df_stack['Dolars'].sum() for _, row in df_stack.iterrows(): if row['Country'] == 'Resto': # 自定义Resto的悬停内容,比如把Pct_change改成“无变化” text = f"<b>{row['Country']}</b><br>Dolars: ${row['Dolars']:,.2f}<br>Percent: {row['Dolars']/total_dolars:.1%}<br>Pct_change: 无变化" else: text = f"<b>{row['Country']}</b><br>Dolars: ${row['Dolars']:,.2f}<br>Percent: {row['Dolars']/total_dolars:.1%}<br>Pct_change: {row['Pct_change']:.1%}" hover_texts.append(text) fig = go.Figure(data=[go.Pie( labels=df_stack["Country"], values=df_stack['Dolars'], hole=.5, hovertext=hover_texts, # 传入自定义的悬停文本列表 hovertemplate="%{hovertext}<extra></extra>" # 直接引用hovertext )]) fig.update_layout( title_text = "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.show()
方法2:拆分多个Pie trace(不推荐)
把“Resto”单独做成一个Pie trace,其他扇区做成另一个,这样就能用update_traces单独修改它的hovertemplate。但这种方法会破坏饼图的整体性,交互逻辑也会变,只适合特殊场景:
import pandas as pd import plotly.graph_objects as go import numpy as np 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] }) # 拆分数据为Resto和其他国家 df_resto = df_stack[df_stack['Country'] == 'Resto'] df_others = df_stack[df_stack['Country'] != 'Resto'] fig = go.Figure() # 添加其他国家的trace,用默认悬停模板 fig.add_trace(go.Pie( labels=df_others["Country"], values=df_others['Dolars'], hole=.5, customdata=np.transpose([df_others["Pct_change"]]), hovertemplate="<b>%{label}</b> <br>Dolars: $%{value:,.2f}" "<br>Percent: %{percent:.1%}" "<br>Pct_change: %{customdata[0]:.1%}" "<extra></extra>", domain={'x': [0, 1], 'y': [0, 1]} # 确保两个trace在同一区域显示 )) # 添加Resto的trace,设置自定义悬停模板 fig.add_trace(go.Pie( labels=df_resto["Country"], values=df_resto['Dolars'], hole=.5, hovertemplate="<b>%{label}</b> <br>Dolars: $%{value:,.2f}" "<br>Percent: %{percent:.1%}" "<br>Pct_change: 无变化" "<extra></extra>", domain={'x': [0, 1], 'y': [0, 1]} )) fig.update_layout( title_text = "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.show()
内容的提问来源于stack exchange,提问作者Keynes is not dead
相关产品推荐
相关产品推荐

