悬停模板='大陆:%{df['大陆']}
'+'国家:%{df['国家']}
'+'gdpPercap:%{x:,.4f}
'+'lifeExp:%{y} '+''
我正在尝试使用hovertemplate 来自定义悬停信息。但是我无法让它显示我想要的内容。我正在让 x 和 y 正常工作。但我不知道如何将其他字段添加到悬停模板中。任何帮助,将不胜感激。
import numpy as np
df = df[df['year'] == 1952]
customdata = np.stack((df['continent'], df['country']), axis=-1)
fig = go.Figure()
for i in df['continent'].unique():
df_by_continent = df[df['continent'] == i]
fig.add_trace(go.Scatter(x=df_by_continent['gdpPercap'],
y=df_by_continent['lifeExp'],
mode='markers',
opacity=.7,
marker = {'size':15},
name=i,
hovertemplate=
'Continent: %{customdata[0]}<br>'+
'Country: %{customdata[1]}<br>'+
'gdpPercap: %{x:,.4f} <br>'+
'lifeExp: %{y}'+
'<extra></extra>',
))
fig.update_layout(title="My Plot",
xaxis={'title':'GDP Per Cap',
'type':'log'},
yaxis={'title':'Life Expectancy'},
)
fig.show()
Run Code Online (Sandbox Code Playgroud)
更新了更多代码。第一个答案仅返回 comdata 的文本值不起作用。
Fla*_*ino 16
请参阅下面的附加示例,了解如何customdata根据问题中包含的代码使用多个跟踪。请注意,您实际上需要将 添加到customdata图形迹线中才能在 中使用它,这也在Derek O的答案hovertemplate中显示。
import numpy as np
import pandas as pd
import plotly.graph_objects as go
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminderDataFiveYear.csv')
df = df[df['year'] == 1952]
fig = go.Figure()
for continent in df['continent'].unique():
df_by_continent = df[df['continent'] == continent]
fig.add_trace(
go.Scatter(
x=df_by_continent['gdpPercap'],
y=df_by_continent['lifeExp'],
customdata=np.stack((df_by_continent['country'], df_by_continent['pop']), axis=-1),
mode='markers',
opacity=0.7,
marker={'size': 15},
name=continent,
hovertemplate='<b>Country</b>: %{customdata[0]}<br>' +
'<b>Population</b>: %{customdata[1]:,.0f}<br>' +
'<b>GDP</b>: %{x:$,.4f}<br>' +
'<b>Life Expectancy</b>: %{y:,.2f} Years' +
'<extra></extra>',
)
)
fig.update_layout(
xaxis={'title': 'GDP Per Cap', 'type': 'log'},
yaxis={'title': 'Life Expectancy'},
)
fig.write_html('fig.html', auto_open=True)
Run Code Online (Sandbox Code Playgroud)
Der*_*k O 11
{x}对于字符串中和{y}之外的任何其他变量hovertemplate,您需要创建一个名为的变量customdata,它是 DataFrame 列的 numpy 数组(df['continent'], df['country']在您的情况下),并传递customdata=customdata给fig.update_layout. 这是 @empet 在他的 Plotly 论坛答案中建议的。
你可以尝试这样的事情:
import numpy as np
import pandas as pd
import plotly.express as px
df = px.data.gapminder()
customdata = np.stack((df['continent'], df['country']), axis=-1)
fig = px.scatter(df, x="gdpPercap", y="lifeExp")
hovertemplate = ('Continent: %{customdata[0]}<br>' +
'Country: %{customdata[1]}<br>' +
'gdpPercap: %{x:,.4f} <br>' +
'lifeExp: %{y}' +
'<extra></extra>')
fig.update_traces(customdata=customdata, hovertemplate=hovertemplate)
fig.show()
Run Code Online (Sandbox Code Playgroud)