簡體   English   中英

Plotly:在懸停模板中包含附加數據

[英]Plotly: Including additional data in hovertemplate

在此處輸入圖像描述 hovertemplate='大陸:%{df['大陸']}
'+ '國家:%{df['country']}
'+ 'gdpPercap: %{x:,.4f}
'+ 'lifeExp: %{y}'+ ''

我正在嘗試使用 hovertemplate 自定義 hover 信息。 但是我無法讓它顯示我想要的東西。 我讓 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()

更新了更多代碼。 第一個答案僅返回 comdata 的文本值不起作用。

對於hovertemplate字符串中除{x}{y}之外的任何其他變量,您需要創建一個名為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()

在此處輸入圖片說明

見下文對如何使用另外的例子中customdata基於包含在你的問題的多個代碼的痕跡。 請注意,您實際上需要將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)

在此處輸入圖片說明

僅使用 pandas/python 的先前答案的變體:

customdata = list(df[['continent','country']].to_numpy())

然后使用引用 customdata 的模板組合您的圖形,如其他答案。 對於變化,這里有一個 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'}
                                           )
                            )
    )
    )]
)

您可以直接將格式化文本傳遞給text參數,而不是使用customdata + hovertemplate 我發現這更簡單,更強大 - 例如,如果您不希望所有元素具有完全相同的格式。

所以這實際上有效:

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,
   ...
)

text元素不支持完整的 HTML,但我看到它至少支持<br><b>標簽。 它似乎支持<h1>, <nbsp>, <hr>標簽。

我相信hovertemplate也是如此。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM