Zolzaya Luvsandorj
Zolzaya Luvsandorj

Reputation: 635

Hover format for hover data in Plotly | Python

I'm trying to format the hover values to show only 2 decimal place for a graph. I was able to format values corresponding x and y values to 2 decimal place. My question is how to format the additional hover data to 2 decimal place?

import numpy as np
import plotly.express as px

x = 0.01001*np.arange(5)
y = 0.5*x
hover_data = [y*3]

fig = px.area(x=x, y=y, hover_data=hover_data)
fig.update_layout(
    xaxis=dict(hoverformat='.2f'),
    yaxis=dict(hoverformat='.2f')
)
fig.show()

The image below may clarify what I mean: enter image description here

Upvotes: 1

Views: 3228

Answers (1)

vestland
vestland

Reputation: 61074

In your case, you can use:

fig.data[0].hovertemplate = 'x=%{x}<br>y=%{y}<br>hover_data_0=%{customdata[0]:.2f}<extra></extra>'

A more flexible approach for multiple traces:

fig.update_traces(hovertemplate = 'x=%{x}<br>y=%{y}<br>hover_data_0=%{customdata[0]:.2f}<extra></extra>')

If you're the kind of pythonista that prefers lambda functions, you can also go for:

fig.for_each_trace(lambda t: t.update(hovertemplate = 'x=%{x}<br>y=%{y}<br>hover_data_0=%{customdata[0]:.2f}<extra></extra>'))

enter image description here

Complete code

import numpy as np
import plotly.express as px

x = 0.01001*np.arange(5)
y = 0.5*x
hover_data = [y*3]

fig = px.area(x=x, y=y, hover_data=hover_data)
fig.update_layout(
    xaxis=dict(hoverformat='.2f'),
    yaxis=dict(hoverformat='.2f')
)

fig.data[0].hovertemplate = 'x=%{x}<br>y=%{y}<br>hover_data_0=%{customdata[0]:.2f}<extra></extra>'

fig.show()

Upvotes: 3

Related Questions