user13747020
user13747020

Reputation:

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

Upvotes: 10

Views: 17326

Answers (3)

Hamzah Al-Qadasi
Hamzah Al-Qadasi

Reputation: 9806

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'})

Upvotes: 1

Kaustubh Lohani
Kaustubh Lohani

Reputation: 655

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

Upvotes: 13

M. Forsythe
M. Forsythe

Reputation: 21

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.

Upvotes: 1

Related Questions