Hopefully you can see that Iām trying add the mean, median, and number of units into the tooltip from a pandas data frame. Obviously I can have two through using values and custom data, but I was wondering if there was a way to increase the amount of data/information in the tooltip as per the below function:
def genSankey(df,cat_cols=[],value_cols='',title='Sankey Diagram'):
# maximum of 6 value cols -> 6 colors
colorPalette = ['#FFD43B','#646464','#4B8BBE','#306998']
labelList = []
colorNumList = []
for catCol in cat_cols:
labelListTemp = list(set(df[catCol].values))
colorNumList.append(len(labelListTemp))
labelList = labelList + labelListTemp
# remove duplicates from labelList
labelList = list(dict.fromkeys(labelList))
# define colors based on number of levels
colorList = []
for idx, colorNum in enumerate(colorNumList):
colorList = colorList + [colorPalette[idx]]*colorNum
# transform df into a source-target pair
for i in range(len(cat_cols)-1):
if i==0:
sourceTargetDf = df[[cat_cols[i],cat_cols[i+1],value_cols[i],value_cols[i+1]]]
sourceTargetDf.columns = ['source','target','avglaghrs','coils']
else:
tempDf = df[[cat_cols[i],cat_cols[i+1],value_cols[i],value_cols[i+1]]]
tempDf.columns = ['source','target','avglaghrs','coils']
sourceTargetDf = pd.concat([sourceTargetDf,tempDf])
sourceTargetDf = sourceTargetDf.groupby(['source','target']).agg({'avglaghrs':['mean','median'],'coils':'nunique'}).reset_index()
# add index for source-target pair
sourceTargetDf['sourceID'] = sourceTargetDf['source'].apply(lambda x: labelList.index(x))
sourceTargetDf['targetID'] = sourceTargetDf['target'].apply(lambda x: labelList.index(x))
# creating the sankey diagram
data = dict(
type='sankey',
valueformat = ".2f",
valuesuffix = "Hrs",
node = dict(
pad = 15,
thickness = 20,
line = dict(
color = "black",
width = 0.5
),
label = labelList,
color = colorList
),
link = dict(
source = sourceTargetDf['sourceID'],
target = sourceTargetDf['targetID'],
value = sourceTargetDf['avglaghrs']['mean'],
customdata = sourceTargetDf['coils']['nunique'],
hovertemplate = '%{customdata} coil(s) spent %{value} on<br />'+
'average to get from %{source.label}<br />'+
'to %{target.label}. %{median}<br />'+
'was the middle value.<extra></extra>'
)
)
layout = dict(
title = title,
font = dict(
size = 10
)
)
fig = dict(data=[data], layout=layout)
return fig
Thanks.