1

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

1 Answer 1

3

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()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.