First of all, I am new to plotly and I am enjoying it a lot. but there is one thing that is concerning me.
I have created a barchart using plotly express. I have added the custom_data at the time of creation(basically its my df.columns. so it was custom_data = df.columns).
no I have a function custom_tooltip()
this takes the dataframe and will give the hovertemplate to display the custom tooltip.
the function goes like this
def custom_tooltip(fig, df, to_display)
col = list(df.columns)
hover_template_string = str()
for i, display_name in to_display.items():
hover_template_string += display_name + ": %{customdata[col.index(i)]} <br>"
this code is not working since it is not refering the the col variable in the function. I need to take the position of the customdata dynamically. hence I am doing this.
If I am hardcoding the data, it is working fine. like
I need to make it dynamic. since the columns are placed as per the dataframe in the custom_data at the time of creation of fig and also in the col, taking indexing will work fine. but I am not able to access the col data in the function. I also tried f-string and it is also not working.
def custom_tooltip(fig,df,to_display, is_detailed = False):
"""
This Function overrides the inbuild or pre-made tool tip of plotly.
fig : graph object that is plotted
df : dataframe that is used to plot
to_display : dict of columns with its custom display
is_detailed : Accepts True or False. If needed custom display text, make it to True.
All the special datatypes like int, datetime64[s] is handled properly. the function assumes all other datatype in the dataframe are of the datatype string.
if there is any other special datatype, handle them accordingly in the function.
"""
col = list(df.columns)
hover_template_string = str()
for i, display_name in to_display.items():
if df[i].dtype == "int64": #handling special data type : Int
if is_detailed:
hover_template_string += display_name + ":"
hover_template_string += "%{customdata[" + f"{col.index(i)}" + "]:,.0f} <br>"
elif df[i].dtype == "datetime64[s]": #handling special Data type : datetime64[s]
if is_detailed:
hover_template_string += display_name + ":"
hover_template_string += "%{customdata[" + f"{col.index(i)}" + "]|%B %d, %Y} <br>"
else:#handling all other data type : mostly strings.
if is_detailed:
hover_template_string += display_name + ":"
hover_template_string += "%{customdata[" + f"{col.index(i)}" + "]} <br>"
hover_template_string += "<extra></extra>"
fig.update_traces(hovertemplate = hover_template_string)
print("Sucessfully Added the tooltip")