[英]Plotly AttributeError: 'Figure' object has no attribute 'update_traces'
[英]How to target a specific trace in pie chart by name when using update_traces() selector attribute?
這個想法是僅在“Resto”跟蹤中更改 hover 模板。 這是一個可重現的例子:
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!!!
與 Scatter traces 不同,最后一行代碼無法解決問題。
fig.update_traces(hovertemplate=None, selector=dict(name = 'Resto')) #It won't work!!!
r-beginners
是對的,我想補充一些我希望會感興趣的細節。
通常,獨特的懸停模板只能應用於特定的軌跡。 因此,只要您在圖形 object 中有不同的軌跡,就可以將您想要的任何懸停模板應用於每個軌跡。 不幸的是,一個 Plotly 餅圖只包含一個軌跡,盡管它可能看起來不像那樣,因為餅圖中有不同的 colors。
您的代碼中有一些細節揭示了這些東西是如何聯系在一起的。 當您使用go.Figure(go.Pie())
構建餅圖時,您正在創建一個包含一條軌跡的圖 object。
如果您使用fig.data
查看餅圖的結構,您將看到hovertemplate
如何與那里唯一的痕跡相關聯:
(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])
}),)
而fig.update_traces(selector=...
可能會為您做的是將您想要的 hovertemplate 應用於圖 object 中的跟蹤。如果您嘗試使用fig.add_trace
構建一個包含多個跟蹤的餅圖,如下所示:
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]))
然后每個fig.add_trace
只會覆蓋圖中 object 中的單個現有跟蹤,因此那里也沒有太大幫助。
我希望這可以澄清一些事情,並且您能夠找到其他方法來傳達可視化中的信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.