简体   繁体   中英

Plotly -Round hover decimals in charts

How do you round numbers for display in a plotly graph? I included an MRE below. Essentially I wanted rounded numbers to appear when the user hovers over the bar.

import plotly.express as px
import pandas as pd
df = pd.DataFrame({'num': [1, 2, 3],
                   'sqrt': pd.Series([1, 2, 3]) ** 0.5})
fig = px.bar(df, x='num', y='sqrt', title='Square root')
fig.show()

You can do it two ways like this:

METHOD-1: Using pd.series.round function.

import plotly.express as px
import pandas as pd
df = pd.DataFrame({'num': [1, 2, 3],
                   'sqrt': (pd.Series([1, 2, 3]) ** 0.5).round(2)})
fig = px.bar(df, x='num', y='sqrt', title='Square root')
fig.show()

METHOD-2: Using python builtin round function. For this to work I will have to use list comprehension instead of pandas series . As series doesn't support it directly.

import plotly.express as px
import pandas as pd
df = pd.DataFrame({'num': [1, 2, 3],
                   'sqrt': [round(x**(1/2),2) for x in [1,2,3]]})
fig = px.bar(df, x='num', y='sqrt', title='Square root')
fig.show()

EDIT :

METHOD-3: As answered by @M. Forsythe below you can also do it using hover_data parameter of plotly.

import plotly.express as px
import pandas as pd
df = pd.DataFrame({'num': [1, 2, 3],
                   'sqrt': pd.Series([1, 2, 3]) ** 0.5})
fig = px.bar(df, x='num', y='sqrt', title='Square root',hover_data={'sqrt':':.2f'})
fig.show()

For plotly express this is covered in the hover format documentation in the section titled “Disabling or customizing hover of columns in plotly express” ( https://plotly.com/python/hover-text-and-formatting/ )

Note that the format strings are d3 format strings, not python f-string formats.

To round your numbers, you can use r with hover_data like that:

fig = px.bar(df, x='num', y='sqrt', hover_data={'sqrt':':.3r'})

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