Skip to content

hovertemplate.py #154

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Nov 2, 2019
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
128 changes: 126 additions & 2 deletions python/hover-text-and-formatting.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ jupyter:
extension: .md
format_name: markdown
format_version: '1.1'
jupytext_version: 1.1.7
jupytext_version: 1.2.1
kernelspec:
display_name: Python 3
language: python
Expand All @@ -20,7 +20,7 @@ jupyter:
name: python
nbconvert_exporter: python
pygments_lexer: ipython3
version: 3.6.5
version: 3.7.3
plotly:
description: How to use hover text and formatting in Python with Plotly.
display_as: file_settings
Expand Down Expand Up @@ -104,5 +104,129 @@ fig.update_yaxes(hoverformat=".2f")
fig.show()
```

### Customize tooltip text with a hovertemplate

To customize the tooltip on your graph you can use [hovertemplate](https://plot.ly/python/reference/#pie-hovertemplate), 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](https://github.com/d3/d3-3.x-api-reference/blob/master/Formatting.md#d3_forma), and `date` in [d3-time-fomrat's syntax](https://github.com/d3/d3-3.x-api-reference/blob/master/Time-Formatting.md#format).
Hovertemplate customize the tooltip text vs. [texttemplate](https://plot.ly/python/reference/#pie-texttemplate) which customizes the text that appears on your chart.

```python
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>'+
'<b>%{text}</b>',
text = ['Custom text {}'.format(i + 1) for i in range(5)],
showlegend = False))

fig.add_trace(go.Scatter(
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))

fig.update_layout(title = "Set hover text with hovertemplate")

fig.show()
```

```python
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}"
))

fig.show()
```

### Advanced Hover Template
The following example shows how to format hover template. [Here](https://plot.ly/python/v3/hover-text-and-formatting/#dash-example) is an example to see how to format hovertemplate in Dash.

```python
import plotly.graph_objects as go
import plotly.express as px
import pandas as pd
import math

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

bubble_size = []

for index, row in df_2007.iterrows():
bubble_size.append(math.sqrt(row['pop']))

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():
fig.add_trace(go.Scatter(
x=continent['gdpPercap'],
y=continent['lifeExp'],
name=continent_name,
text=df_2007['continent'],
hovertemplate=
"<b>%{text}</b><br><br>" +
"GDP per Capita: %{y:$,.0f}<br>" +
"Life Expectation: %{x:.0%}<br>" +
"Population: %{marker.size:,}" +
"<extra></extra>",
marker_size=continent['size'],
))

fig.update_traces(
mode='markers',
marker={'sizemode':'area',
'sizeref':10})

fig.update_layout(
xaxis={
'title':'GDP per capita',
'type':'log'},
yaxis={'title':'Life Expectancy (years)'})

fig.show()
```

### Set Hover Template in Mapbox
```python
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>" ))

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

fig.show()
```

#### Reference
See https://plot.ly/python/reference/ for more information and chart attribute options!