[英]Plotly: Including additional data in hovertemplate
hovertemplate= 'Continent: %{df['continent']} hovertemplate='大陆:%{df['大陆']}
'+ 'Country: %{df['country']} '+ '国家:%{df['country']}
'+ 'gdpPercap: %{x:,.4f} '+ 'gdpPercap: %{x:,.4f}
'+ 'lifeExp: %{y}'+ '' '+ 'lifeExp: %{y}'+ ''
I'm trying to use hovertemplate to customize hover information.我正在尝试使用 hovertemplate 自定义 hover 信息。 However I can't get it to display what I want.但是我无法让它显示我想要的东西。 I am getting x & y to work well.我让 x & y 工作得很好。 I can't figure out how to add other fields to the hovertemplate though.我不知道如何将其他字段添加到悬停模板。 Any help would be appreciated.任何帮助,将不胜感激。
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()
Updated with more code.更新了更多代码。 The first answer didn't work just returning the text value of comdata.第一个答案仅返回 comdata 的文本值不起作用。
For any other variables besides {x}
and {y}
in the hovertemplate
string, you'll want to create a variable called customdata
which is a numpy array of the DataFrame columns ( df['continent'], df['country']
in your case), and pass customdata=customdata
to fig.update_layout
.对于hovertemplate
字符串中除{x}
和{y}
之外的任何其他变量,您需要创建一个名为customdata
的变量,它是 DataFrame 列的 numpy 数组( df['continent'], df['country']
在您的情况下),并将customdata=customdata
传递给fig.update_layout
。 This is suggested by @empet in his Plotly forum answer here .这是由@empet在他Plotly论坛回答表明这里。
You can try something like:您可以尝试以下操作:
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()
See below for an additional example of how to use customdata
with multiple traces based on the code included in your question.见下文对如何使用另外的例子中customdata
基于包含在你的问题的多个代码的痕迹。 Note that you actually need to add the customdata
to the figure traces in order to use it in the hovertemplate
, this was also shown in Derek O 's answer.请注意,您实际上需要将customdata
添加到图形跟踪中才能在hovertemplate
使用它,这也显示在Derek O的回答中。
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)
A variation of the previous answers using just pandas/python:仅使用 pandas/python 的先前答案的变体:
customdata = list(df[['continent','country']].to_numpy())
Then compose your figure with a template referring to customdata as in the other answers.然后使用引用 customdata 的模板组合您的图形,如其他答案。 For variation here's an example with Scatter3D and adding data from two columns of a dataframe:对于变化,这里有一个 Scatter3D 示例,并从数据帧的两列添加数据:
import plotly.graph_objects as go
customdata_set = list(df[['transaction','type']].to_numpy())
fig = go.Figure(
data=[go.Scatter3d(x=df.time,
y=df.source,
z=df.dest,
hovertemplate='<i>Source:</i>: %{y:i}<br>' +
'<i>Destination:</i>: %{z:i}<br>' +
'<i>Amount:</i>: $%{text}<br>' +
'<i>Txn #:</i>: %{customdata[0]}<br>' +
'<i>Txn Type:</i>: %{customdata[1]}<br>' +
'<i>Date:</i>: %{x|%Y-%m-%d}',
text=(df.amount).to_numpy(),
customdata = customdata_set,
mode='markers',
marker=dict(
color=moat_sql.tx_amount,
size=4,
opacity=.8,
showscale=True,
colorscale='Viridis',
colorbar=dict(
title=dict(text='Log Txn Amount',
side='bottom',
font={'color': 'red'}
)
)
)
)]
)
Instead of using customdata + hovertemplate
, you can just pass formatted text to the text
parameter directly.您可以直接将格式化文本传递给text
参数,而不是使用customdata + hovertemplate
。 I found this simpler, and more powerful - for example if you don't want the exact same formatting for all elements.我发现这更简单,更强大 - 例如,如果您不希望所有元素具有完全相同的格式。
So this actually works:所以这实际上有效:
text = your_df.map(
lambda row: f'<i>Source:</i>: %{row.source:i}<br>' +
f'<i>Destination:</i>: %{row.z:i}<br>' +
f'<i>Amount:</i>: $%{row.amount}<br>' +
f'<i>Txn #:</i>: %{row.txn}<br>' +
f'<i>Txn Type:</i>: %{row.txn_type}<br>' +
f'<i>Date:</i>: %{row.date|%Y-%m-%d}',
axis='columns'
)
go.Scatter3d(
...,
text=text,
...
)
The text
element doesn't support full HTML, but I've seen it support at least the <br>
and <b>
tags. text
元素不支持完整的 HTML,但我看到它至少支持<br>
和<b>
标签。 It does not seem to support <h1>, <nbsp>, <hr>
tags.它似乎不支持<h1>, <nbsp>, <hr>
标签。
I believe the same is true for hovertemplate
.我相信hovertemplate
也是如此。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.