Reputation: 101
I would like to format the numbers in the hovertemplate according to their height like this:
The closest I’ve come to what I want is this:
fig.add_trace(
go.Scatter(
x= df.index,
y= df[line],
hovertemplate= (
'%{y:,.2f}' if '%{y:.0f}' < '10' else
'%{y:,.1f}' if '%{y:.0f}' < '100' else
'%{y:,.0f}'
)
)
)
It runs without errors, but it gives me two decimal places for all numbers.
Can anyone help me?
Upvotes: 0
Views: 3224
Reputation: 31236
import pandas as pd
import numpy as np
import plotly.graph_objects as go
line = "a"
df = pd.DataFrame({line: np.random.uniform(0, 200, 200)})
fig = go.Figure()
fig.add_trace(
go.Scatter(
x=df.index,
y=df[line],
hovertemplate=np.select(
[df[line] < 10, df[line] < 100], ["%{y:.2f}", "%{y:.1f}"], "%{y:.0f}"
),
)
)
Upvotes: 3
Reputation: 9826
You can do the conditions outside the plotting and then, add it to the hovertemplate at once:
import plotly.graph_objects as go
y = [0.99, 10.02, 20.04, 130.65, 4.25]
customdata = []
for i in y:
if i < 10:
customdata.append("{:.2f}".format(i))
elif i < 100:
customdata.append("{:.1f}".format(i))
else:
customdata.append("{:.0f}".format(i))
fig.add_trace(
go.Scatter(
x =[0, 1, 2, 3, 4],
y = y,
customdata=customdata,
hovertemplate= ('%{customdata}')
)
)
fig.show()
Upvotes: 2