Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plotly: Including additional data in hovertemplate

Tags:

python

plotly

enter image description here hovertemplate= 'Continent: %{df['continent']}
'+ 'Country: %{df['country']}
'+ 'gdpPercap: %{x:,.4f}
'+ 'lifeExp: %{y}'+ ''

I'm trying to use hovertemplate to customize hover information. However I can't get it to display what I want. I am getting x & y to work well. 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.

like image 641
David 54321 Avatar asked Feb 03 '26 05:02

David 54321


1 Answers

See below for an additional example of how to use customdata with multiple traces based on the code included in your question. 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.

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)

enter image description here

like image 99
Flavia Giammarino Avatar answered Feb 04 '26 17:02

Flavia Giammarino



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!