amb*_*hed 9 python plotly plotly-python
我正在使用plotly.express饼图帮助页面iso_num中的示例,并尝试向hover_data属性添加额外的元素(iso_num是gapminder数据框中的int64列)
import plotly.express as px
df = px.data.gapminder().query("year == 2007").query("continent == 'Americas'")
fig = px.pie(df, values='pop', names='country',
title='Population of American continent',
hover_data=['lifeExp','iso_num'], labels={'lifeExp':'life expectancy','iso_num':'iso num'
})
fig.update_traces(textposition='inside', textinfo='percent+label')
fig.show()
Run Code Online (Sandbox Code Playgroud)
将鼠标悬停在饼图的切片上会给出以下结果:
其中iso numvalue 是%{customdata[1]}而不是列中的数值。
我缺少什么?
谢谢!
小智 7
我也找到了一种使用 Plotly Express 饼图来做到这一点的方法。您可以使用update_traces来定义hover_template. 似乎存在对hover_data/ 的多个值进行拆分的问题custom_data,并且所有值仅出现在 0 索引处,即两个值都位于customdata[0]。
import plotly.express as px
df = px.data.gapminder().query("year == 2007").query("continent == 'Americas'")
fig = px.pie(df, values='pop', names='country',
title='Population of American continent',
custom_data=['lifeExp','iso_num'], labels={'lifeExp':'life expectancy','iso_num':'iso num'
})
fig.update_traces(textposition='inside', textinfo='percent+label',\
hovertemplate = "Country:%{label}: <br>Population: %{value} </br>(life expentancy, iso num) : %{customdata}"
)
fig.show()
Run Code Online (Sandbox Code Playgroud)
悬停时:
哦,馅饼悬停真是一团糟
这似乎已经解决了。但也许不是为了px.pie()?我尝试了多种方法,但我只能使用customdata + hovertemplate方法来工作go.Pie,而不适用于px.Pie. 下面演示了如何将值分配给customdata以使任何未分配的变量可go.Pie()用于自定义悬停模板:
阴谋:
代码:
import plotly.graph_objects as go
import plotly.express as px
df = px.data.gapminder().query("year == 2007").query("continent == 'Americas'")
fig = go.Figure(go.Pie(
name = "",
values = df['pop'],
labels = df['country'],
customdata=df['iso_num'],
hovertemplate = "Country:%{label}: <br>Population: %{value} </br> iso num:%{customdata}"
))
fig.show()
Run Code Online (Sandbox Code Playgroud)