I am using the following code:
import plotly.express as px
df = px.data.tips()
fig = px.treemap(df, path=[px.Constant("all"), 'day', 'time', 'sex'], values='total_bill')
fig.update_traces(root_color="lightgrey")
fig.update_layout(margin = dict(t=50, l=25, r=25, b=25))
fig.update_traces(textinfo="label+text+value")
fig.show()
Which generates the diagram:
Here I can display the values in the innermost squares (Eg. Under Male and Female) using textinfo. However, I want to also display the values add every level of the hierarchy. Eg. under dinner where it is a sum of the values of Male + Female and so on.
Eg.:
Dinner = Male + Female
Sat = Lunch + dinner
etc.
Havenβt been able to figure out whether this is possible, and if so, how to do that. Any help will be appreciated.
Have you tried:
fig.update_traces(textinfo='label+text+value+percent root')
Yes. update_traces only adds it to the innermost layer. Adding the percent root
option will only add that data alng with the label + text + value to the innermost layer and not to the intermediate layers.
I think you may need to pre-compute the intermediate sums and use it as a workaround to add it to the labels.
import plotly.express as px
import pandas as pd
df = px.data.tips()
# Calc. intermediate sums
df_total = df.groupby(['day', 'time', 'sex']).total_bill.sum().reset_index()
df_time = df.groupby(['day', 'time']).total_bill.sum().reset_index().rename(columns={'total_bill':'total_time'})
df_day = df.groupby(['day']).total_bill.sum().reset_index().rename(columns={'total_bill':'total_day'})
# Merge df to have all totals in one place
df_total = pd.merge(df_total, df_time, on=['day', 'time'])
df_total = pd.merge(df_total, df_day, on=['day'])
# Create labels with totals
df_total['sex'] = df_total['sex'] + ' (' + df_total['total_bill'].astype(str) + ')'
df_total['time'] = df_total['time'] + ' (' + df_total['total_time'].astype(str) + ')'
df_total['day'] = df_total['day'] + ' (' + df_total['total_day'].astype(str) + ')'
fig = px.treemap(df_total, path=[px.Constant("all"), 'day', 'time', 'sex'], values='total_bill')
fig.update_traces(root_color="lightgrey")
fig.update_layout(margin = dict(t=50, l=25, r=25, b=25))
fig.show()