Skip to content

Commit d628817

Browse files
Update hover-text-and-formatting.md
1) added an example that formats the elements of custom_data in plotly express 2) fixed a bug in the "advanced hovertemplate" example which caused it to display the square root of population. Modified that example to follow the main dataframe is called "df" convention. Added a country name field to that example and comments about the usage of key parameters. 3) I did not remove the "Adding other data to the hover with customdata and a hovertemplate" example, but I believe it is now redundant and that the revised ### Advanced Hover Template example is more compliant with expectations like using meaningful data over random data. If you removed it, it would make sense to rename "Advanced Hover Template" to include the phrase: "Adding other data to the hover with customdata and a hovertemplate"
1 parent 44a1dc3 commit d628817

File tree

1 file changed

+77
-16
lines changed

1 file changed

+77
-16
lines changed

doc/python/hover-text-and-formatting.md

Lines changed: 77 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -252,6 +252,58 @@ print("user_defined hovertemplate:", fig.data[0].hovertemplate)
252252
fig.show()
253253
```
254254

255+
### Specifying the formatting and labeling of custom fields in a Plotly Express figure using a hovertemplate
256+
257+
This example adds custom fields to a Plotly Express figure using the custom_data parameter and then adds a hover template that applies d3 formats to each element of the customdata[n] array and uses HTML to customize the fonts and spacing.
258+
259+
```
260+
# %%
261+
import plotly.graph_objects as go
262+
import plotly.express as px
263+
import pandas as pd
264+
import math
265+
import numpy as np
266+
267+
data = px.data.gapminder()
268+
df = data[data['year']==2007]
269+
df = df.sort_values(['continent', 'country'])
270+
271+
df.rename(columns={"gdpPercap":'GDP per capita', "lifeExp":'Life Expectancy (years)'}, inplace=True)
272+
273+
fig=px.scatter(df,
274+
x='GDP per capita',
275+
y='Life Expectancy (years)',
276+
color='continent',
277+
size=np.sqrt(df['pop']),
278+
# Specifying data to make availabe to the hovertemplate
279+
# The px custom_data parameter has an underscore, whike the analogous graph objects customdata parameter has no underscore.
280+
# The px custom_data parameter is a list of column names in the data frame, while the graph objects customdata parameter expects a data frame or a numpy array.
281+
custom_data=['country', 'continent', 'pop'],
282+
)
283+
284+
# Plotly express does not have a hovertemplate paramter in the graph creation function, so we apply the template with update_traces
285+
fig.update_traces(
286+
hovertemplate =
287+
"<b>%{customdata[0]}</b><br>" +
288+
"<b>%{customdata[1]}</b><br><br>" +
289+
"GDP per Capita: %{x:$,.0f}<br>" +
290+
"Life Expectation: %{y:.0f}<br>" +
291+
"Population: %{customdata[2]:,.0f}" +
292+
"<extra></extra>",
293+
mode='markers',
294+
marker={'sizemode':'area',
295+
'sizeref':10},
296+
)
297+
298+
fig.update_layout(
299+
xaxis={
300+
'type':'log'},
301+
)
302+
303+
fig.show()
304+
```
305+
306+
255307
### Hover Templates with Mixtures of Period data
256308

257309
*New in v5.0*
@@ -288,9 +340,8 @@ fig.show()
288340

289341
### Advanced Hover Template
290342

291-
The following example shows how to format a hover template.
292-
293-
```python
343+
This produces the same graphic as in "Specifying the formatting and labeling of custom fields in a Plotly Express figure using a hovertemplate" above, but does so with the `customdata` and `text` parameters of `graph_objects`. It shows how to specify columns from a dataframe to include in the customdata array using the df[["col_i", "col_j"]] subsetting notation. It then references those variables using e.g. %{customdata[0]} in the hovertemplate. It includes comments about major differences between the parameters used by `graph_objects` and `plotly.express`.
344+
```
294345
import plotly.graph_objects as go
295346
import plotly.express as px
296347
import pandas as pd
@@ -312,21 +363,31 @@ continent_data = {continent:df_2007.query("continent == '%s'" %continent)
312363
313364
fig = go.Figure()
314365
315-
for continent_name, continent in continent_data.items():
316-
fig.add_trace(go.Scatter(
317-
x=continent['gdpPercap'],
318-
y=continent['lifeExp'],
319-
name=continent_name,
320-
text=continent['continent'],
321-
hovertemplate=
322-
"<b>%{text}</b><br><br>" +
323-
"GDP per Capita: %{x:$,.0f}<br>" +
324-
"Life Expectation: %{y:.0%}<br>" +
325-
"Population: %{marker.size:,}" +
326-
"<extra></extra>",
327-
marker_size=continent['size'],
366+
for continent_name, df in continent_data.items():
367+
fig.add_trace(
368+
go.Scatter(
369+
x=df['gdpPercap'],
370+
y=df['lifeExp'],
371+
marker_size=df['size'],
372+
name=continent_name,
373+
374+
# The next three parameters specify the hover text
375+
# Text supports just one customized field per trace, but is simple to implement
376+
text=df['continent'],
377+
# Custom data supports multiple fields through numeric indices in the hovertemplate
378+
# If I were not looking for an opportunity to demonstrate the text parameter,
379+
# I would likely just add continent as a third customdata field.
380+
customdata=df[['country','pop']],
381+
hovertemplate=
382+
"<b>%{customdata[0]}</b><br>" +
383+
"<b>%{text}</b><br><br>" +
384+
"GDP per Capita: %{x:$,.0f}<br>" +
385+
"Life Expectancy: %{y:.0f}<br>" +
386+
"Population: %{customdata[1]:,.0f}" +
387+
"<extra></extra>",
328388
))
329389
390+
330391
fig.update_traces(
331392
mode='markers',
332393
marker={'sizemode':'area',

0 commit comments

Comments
 (0)