Plotly sunburst chart timedelta field in values ends with scientific notation

Viewed 139

When creating a sunburst chart I want to have a timedelta sum values seen when moving cursor into a part of chart (field 'time' below). Field is type timedelta64[ns]. Works fine with sum aggregations with pandas groupby function. Then I have values like this: 13 days 12:34:15

When I create a plotly sunburst chart and take my cursor over the field I see a scientific notations as below: time_sum: 1.512195e+15

Is there a way to change it? Is there a way to see this 'time' field as a timedelta sum?

Not sure if it's important but I am using Jupyter Notebook.

Example code here:

import plotly.express as px
import pandas as pd

df = pd.DataFrame([
    ['A', 'aa', 'x', 46789],
    ['B', 'aa', 'x', 899],
    ['C', 'aa', 'x', 47],
    ['A', 'aa', 'y', 1034],
    ['A', 'aa', 'y', 9899],
    ['A', 'ab', 'x', 34676],
    ['B', 'ba', 'y', 654],
    ['B', 'ba', 'x', 321442]],
    index=[1, 2, 3, 4, 5, 6, 7, 8],
    columns=['category','subcategory','type', 'time'])
df['time'] = pd.to_timedelta(df['time'], unit = 'S')


fig = px.sunburst(df, path = ['category', 'subcategory', 'type'], values = 'time', 
                  width = 700, height = 700)
fig.show()
1 Answers

You can convert the timedelta values to strings and store these in customdata, then pass customdata to the hovertemplate by using time=%{customdata} in the hovertemplate string.

However, the shape of the underlying data in fig.data[0] is going to be different than the columns of df (because values are repeated), so you'll want to retrieve your timedelta values from fig.data[0].values before converting them to timedelta strings.

import plotly.express as px
import numpy as np
import pandas as pd

df = pd.DataFrame([
    ['A', 'aa', 'x', 46789],
    ['B', 'aa', 'x', 899],
    ['C', 'aa', 'x', 47],
    ['A', 'aa', 'y', 1034],
    ['A', 'aa', 'y', 9899],
    ['A', 'ab', 'x', 34676],
    ['B', 'ba', 'y', 654],
    ['B', 'ba', 'x', 321442]],
    index=[1, 2, 3, 4, 5, 6, 7, 8],
    columns=['category','subcategory','type', 'time'])
df['time'] = pd.to_timedelta(df['time'], unit = 'S')

fig = px.sunburst(df, path = ['category', 'subcategory', 'type'], values = 'time',
                  width = 700, height = 700)

fig.data[0]['customdata'] = np.array([str(pd.Timedelta(val)) for val in fig.data[0].values])

## use customdata to display the time in timedelta
fig.update_traces(
    hovertemplate='labels=%{label}<br>time=%{customdata}<br>parent=%{parent}<br>id=%{id}<extra></extra>'
)
fig.show()

enter image description here

Related