Black Lives Matter. Please consider donating to Black Girls Code today.

Hover Text and Formatting in Python

How to use hover text and formatting in Python with Plotly.

If you're using Dash Enterprise's Data Science Workspaces, you can copy/paste any of these cells into a Workspace Jupyter notebook.
Alternatively, download this entire tutorial as a Jupyter notebook and import it into your Workspace.
Find out if your company is using Dash Enterprise.

New to Plotly?

Plotly is a free and open-source graphing library for Python. We recommend you read our Getting Started guide for the latest installation or upgrade instructions, then move on to our Plotly Fundamentals tutorials or dive straight in to some Basic Charts tutorials.

Hover Labels

One of the most deceptively-power features of interactive visualization using Plotly is the ability for the user to reveal more information about a data point by moving their mouse cursor over the point and having a hover label appear.

There are three hover modes available in Plotly. The default setting is layout.hovermode='closest', wherein a single hover label appears for the point directly underneath the cursor.

Hovermode closest (default mode)

In [1]:
import as px

df ="continent=='Oceania'")

fig = px.line(df, x="year", y="lifeExp", color="country", title="layout.hovermode='closest' (the default)")

Hovermode x or y

If layout.hovermode='x' (or 'y'), a single hover label appears per trace, for points at the same x (or y) value as the cursor. If multiple points in a given trace exist at the same coordinate, only one will get a hover label. In the line plot below we have forced markers to appear, to make it clearer what can be hovered over, and we have disabled the built-in Plotly Express hovertemplate by setting it to None, resulting in a more compact hover label per point:

In [2]:
import as px

df ="continent=='Oceania'")

fig = px.line(df, x="year", y="lifeExp", color="country", title="layout.hovermode='x'")
fig.update_traces(mode="markers+lines", hovertemplate=None)

Unified hovermode

If layout.hovermode='x unified' (or 'y unified'), a single hover label appear, describing one point per trace, for points at the same x (or y) value as the cursor. If multiple points in a given trace exist at the same coordinate, only one will get an entry in the hover label. In the line plot below we have forced markers to appear, to make it clearer what can be hovered over, and we have disabled the built-in Plotly Express hovertemplate by setting it to None, resulting in a more compact entry per point in the hover label:

In [3]:
import as px

df ="continent=='Oceania'")

fig = px.line(df, x="year", y="lifeExp", color="country", title="layout.hovermode='x unified'")
fig.update_traces(mode="markers+lines", hovertemplate=None)
fig.update_layout(hovermode="x unified")

Control hovermode with Dash

Dash is the best way to build analytical apps in Python using Plotly figures. To run the app below, run pip install dash, click "Download" to get the code and run python

Get started with the official Dash docs and learn how to effortlessly style & deploy apps like this with Dash Enterprise.

Change the hovermode below and try hovering over the points:


Selecting a hovermode in a figure created with plotly.graph_objects

The hovermode is a property of the figure layout, so you can select a hovermode no matter how you created the figure, either with or with plotly.graph_objects. Below is an example with a figure created with plotly.graph_objects. If you're not familiar with the structure of plotly figures, you can read the tutorial on creating and updating plotly figures.

In [5]:
import plotly.graph_objects as go
import numpy as np
t = np.linspace(0, 2 * np.pi, 100)
fig = go.Figure()
fig.add_trace(go.Scatter(x=t, y=np.sin(t), name='sin(t)'))
fig.add_trace(go.Scatter(x=t, y=np.cos(t), name='cost(t)'))
fig.update_layout(hovermode='x unified')

Customizing Hover Label Appearance

Hover label text and colors default to trace colors in hover modes other than unified, and can be globally set via the layout.hoverlabel attributes. Hover label appearance can also be controlled per trace in <trace>.hoverlabel.

In [6]:
import as px

df ="continent=='Oceania'")

fig = px.line(df, x="year", y="lifeExp", color="country", title="Custom layout.hoverlabel formatting")


Customizing Hover text with Plotly Express

Plotly Express functions automatically add all the data being plotted (x, y, color etc) to the hover label. Many Plotly Express functions also support configurable hover text. The hover_data argument accepts a list of column names to be added to the hover tooltip, or a dictionary for advanced formatting (see the next section). The hover_name property controls which column is displayed in bold as the tooltip title.

Here is an example that creates a scatter plot using Plotly Express with custom hover data and a custom hover name.

In [7]:
import as px

df_2007 ="year==2007")

fig = px.scatter(df_2007, x="gdpPercap", y="lifeExp", log_x=True,
                 hover_name="country", hover_data=["continent", "pop"])

Disabling or customizing hover of columns in plotly express

hover_data can also be a dictionary. Its keys are existing columns of the dataframe argument, or new labels. For an existing column, the values can be

  • False to remove the column from the hover data (for example, if one wishes to remove the column of the x argument)
  • True to add a different column, with default formatting
  • a formatting string starting with : for numbers d3-format's syntax, and | for dates in d3-time-format's syntax, for example :.3f, |%a.

It is also possible to pass new data as values of the hover_data dict, either as list-like data, or inside a tuple, which first element is one of the possible values described above for existing columns, and the second element correspond to the list-like data, for example (True, [1, 2, 3]) or (':.1f', [1.54, 2.345]).

These different cases are illustrated in the following example.

In [8]:
import as px
import numpy as np
df =
fig = px.scatter(df, x='petal_length', y='sepal_length', facet_col='species', color='species',
                 hover_data={'species':False, # remove species from hover data
                             'sepal_length':':.2f', # customize hover for column of y attribute
                             'petal_width':True, # add other column, default formatting
                             'sepal_width':':.2f', # add other column, customized formatting
                             # data not in dataframe, default formatting
                             'suppl_1': np.random.random(len(df)),
                             # data not in dataframe, customized formatting
                             'suppl_2': (':.3f', np.random.random(len(df)))

Customizing hover text with a hovertemplate

To customize the tooltip on your graph you can use the hovertemplate attribute of graph_objects tracces, which is a template string used for rendering the information that appear on hoverbox. This template string can include variables in %{variable} format, numbers in d3-format's syntax, and date in d3-time-format's syntax. In the example below, the empty <extra></extra> tag removes the part of the hover where the trace name is usually displayed in a contrasting color. The <extra> tag can be used to display other parts of the hovertemplate, it is not reserved for the trace name.

Note that a hovertemplate customizes the tooltip text, while a texttemplate customizes the text that appears on your chart.

Set the horizontal alignment of the text within tooltip with hoverlabel.align.

In [9]:
import plotly.graph_objects as go

fig = go.Figure(go.Scatter(
    x = [1,2,3,4,5],
    y = [2.02825,1.63728,6.83839,4.8485,4.73463],
    hovertemplate =
    '<i>Price</i>: $%{y:.2f}'+
    '<br><b>X</b>: %{x}<br>'+
    text = ['Custom text {}'.format(i + 1) for i in range(5)],
    showlegend = False))

    x = [1,2,3,4,5],
    y = [3.02825,2.63728,4.83839,3.8485,1.73463],
    hovertemplate = 'Price: %{y:$.2f}<extra></extra>',
    showlegend = False))

    hoverlabel_align = 'right',
    title = "Set hover text with hovertemplate")
In [10]:
import plotly.graph_objects as go

fig = go.Figure(go.Pie(
    name = "",
    values = [2, 5, 3, 2.5],
    labels = ["R", "Python", "Java Script", "Matlab"],
    text = ["textA", "TextB", "TextC", "TextD"],
    hovertemplate = "%{label}: <br>Popularity: %{percent} </br> %{text}"

Modifying the hovertemplate of a plotly express figure automatically sets the hovertemplate but you can modify it using the update_traces method of the generated figure. It helps to print the hovertemplate generated by in order to be able to modify it. One can also revert to the default hover information of traces by setting the hovertemplate to None.

In [11]:
import as px

df_2007 ="year==2007")

fig = px.scatter(df_2007, x="gdpPercap", y="lifeExp", log_x=True, color='continent'
print("plotly express hovertemplate:",[0].hovertemplate)
fig.update_traces(hovertemplate='GDP: %{x} <br>Life Expectancy: %{y}') #
fig.update_traces(hovertemplate=None, selector={'name':'Europe'}) # revert to default hover
print("user_defined hovertemplate:",[0].hovertemplate)
plotly express hovertemplate: continent=Asia<br>gdpPercap=%{x}<br>lifeExp=%{y}<extra></extra>
user_defined hovertemplate: GDP: %{x} <br>Life Expectancy: %{y}

Advanced Hover Template

The following example shows how to format hover template. Here is an example to see how to format hovertemplate in Dash.

In [12]:
import plotly.graph_objects as go
import as px
import pandas as pd
import math

data =
df_2007 = data[data['year']==2007]
df_2007 = df_2007.sort_values(['continent', 'country'])

bubble_size = []

for index, row in df_2007.iterrows():

df_2007['size'] = bubble_size
continent_names = ['Africa', 'Americas', 'Asia', 'Europe', 'Oceania']
continent_data = {continent:df_2007.query("continent == '%s'" %continent)
                              for continent in continent_names}

fig = go.Figure()

for continent_name, continent in continent_data.items():
        "<b>%{text}</b><br><br>" +
        "GDP per Capita: %{x:$,.0f}<br>" +
        "Life Expectation: %{y:.0%}<br>" +
        "Population: %{marker.size:,}" +


        'title':'GDP per capita',
    yaxis={'title':'Life Expectancy (years)'})

Adding other data to the hover with customdata and a hovertemplate

go traces have a customdata argument in which you can add an array, which outer dimensions should have the same dimensions as the plotted data. You can then use customdata inside a hovertemplate to display the value of customdata.

In [13]:
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import numpy as np
z1, z2, z3 = np.random.random((3, 7, 7))
customdata = np.dstack((z2, z3))
fig = make_subplots(1, 2, subplot_titles=['z1', 'z2'])
    customdata=np.dstack((z2, z3)),
    hovertemplate='<b>z1:%{z:.3f}</b><br>z2:%{customdata[0]:.3f} <br>z3: %{customdata[1]:.3f} ',
    coloraxis="coloraxis1", name=''),
    1, 1)
    customdata=np.dstack((z1, z3)),
    hovertemplate='z1:%{customdata[0]:.3f} <br><b>z2:%{z:.3f}</b><br>z3: %{customdata[1]:.3f} ',
    coloraxis="coloraxis1", name=''),
    1, 2)
fig.update_layout(title_text='Hover to see the value of z1, z2 and z3 together')

Setting the Hover Template in Mapbox Maps

In [14]:
import plotly.graph_objects as go

token = open(".mapbox_token").read() # you need your own token

fig = go.Figure(go.Scattermapbox(
    name = "",
    mode = "markers+text+lines",
    lon = [-75, -80, -50],
    lat = [45, 20, -20],
    marker = {'size': 20, 'symbol': ["bus", "harbor", "airport"]},
    hovertemplate =
    "<b>%{marker.symbol} </b><br><br>" +
    "longitude: %{lon}<br>" +
    "latitude: %{lat}<br>" ))

    mapbox = {
        'accesstoken': token,
        'style': "outdoors", 'zoom': 1},
    showlegend = False)

Controlling Hover Text with graph_objects and hoverinfo

Prior to the addition of hovertemplate, hover text was controlled via the now-deprecated hoverinfo attribute.

In [15]:
import plotly.graph_objects as go

fig = go.Figure()

    x=[1, 2, 3, 4, 5],
    y=[2, 1, 6, 4, 4],
    hovertext=["Text A", "Text B", "Text C", "Text D", "Text E"],

Spike lines

Plotly supports "spike lines" which link a point to the axis on hover, and can be configured per axis.

In [16]:
import as px

df ="continent=='Oceania'")

fig = px.line(df, x="year", y="lifeExp", color="country", title="Spike lines active")


Spike lines can be styled per axis as well, and the cursor distance setting can be controlled via layout.spikedistance.

In [17]:
import as px

df ="continent=='Oceania'")

fig = px.line(df, x="year", y="lifeExp", color="country", title="Styled Spike Lines")

fig.update_xaxes(showspikes=True, spikecolor="green", spikesnap="cursor", spikemode="across")
fig.update_yaxes(showspikes=True, spikecolor="orange", spikethickness=2)
fig.update_layout(spikedistance=1000, hoverdistance=100)


See for more information and chart attribute options!

What About Dash?

Dash is an open-source framework for building analytical applications, with no Javascript required, and it is tightly integrated with the Plotly graphing library.

Learn about how to install Dash at

Everywhere in this page that you see, you can display the same figure in a Dash application by passing it to the figure argument of the Graph component from the built-in dash_core_components package like this:

import plotly.graph_objects as go # or as px
fig = go.Figure() # or any Plotly Express function e.g.
# fig.add_trace( ... )
# fig.update_layout( ... )

import dash
import dash_core_components as dcc
import dash_html_components as html

app = dash.Dash()
app.layout = html.Div([

app.run_server(debug=True, use_reloader=False)  # Turn off reloader if inside Jupyter