简体   繁体   中英

Python Plotly - number format in hovertemplate with if...else

I would like to format the numbers in the hovertemplate according to their height like this:

  • 2 decimal places if the number is under 10,
  • 1 decimal place if the number is under 100,
  • 0 decimal places if the number is above or equal 100

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?

  • hovertemplate can be an array/list
  • hence you can build an array that is appropriate format for value
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}"
        ),
    )
)

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()

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM