1

I would like to pass a variable, in this case precision for defining the floating points in plotly hovertemplate= "%{y:.2f}.

Is there a way of doing this? Below is a working sample code

import pandas as pd
import plotly.express as px
import plotly.io as pio

pio.renderers.default = "notebook_connected"

df = pd.DataFrame(dict(a=[1,2,3,4,5], b=[0.1,0.22,0.333, 0.4444, 0.55555]))
precision = 2
fig = px.line(df, x="a", y="b")

#         
fig.update_traces(mode="lines", hovertemplate= "%{y:.3f}", hoverinfo="x + y") 
# would like to use a variable to define floating point precision
# Something  like: hovertemplate= "%{y:.precisionf}"

fig.update_layout(
   template="plotly_white",
   title='Sample Plot',
   xaxis_range= [0, 6],
   
   xaxis=dict(
       tickmode="linear",
       dtick=1,
       mirror=True,
       ticks="outside",
       showline=True,
       linewidth=1,
       linecolor="#A6C4EF",
   ),
   yaxis=dict(
       tickmode="linear",
       tick0=5,
       dtick=0.1,
       mirror=True,
       ticks="outside",
       showline=True,
       linewidth=1,
       linecolor="#A6C4EF",
   ),
   
   xaxis_title='a',
   yaxis_title='b',
   legend_title="LEGEND",
   legend=dict(bordercolor="#A6C4EF", borderwidth=1),
   hovermode="x unified",
)

fig.show()

1 Answer 1

5

Use f-strings

precision = 2
fig.update_traces(mode="lines", hovertemplate= f"%{{y:.{precision}f}}", hoverinfo="x + y") 

In f-strings the {{ is an escape sequence for { if you want to add those to your strings.

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.