Search code examples
pythonplotlydatasethoverplotly-python

How to customize hover-template on with what information to show


Here is my dataset:

my demo dataset

After locking my dataframe by year and grouping by month, I proceed with calculating percentage increase/decrease as a new column; it ends up looking like this:

printing 3 dfs

Now for my Plotly plot I use this to display traces and add some hover info:

fig.add_trace(go.Scatter(x=group_dfff.Months, y=group_dfff.Amount, name=i,
                        hovertemplate='Price: $%{y:.2f}'+'<br>Week: %{x}'))

Now as you can see there is an argument hovertemplate where I can pass my x and y... However, I can't figure out how to include my PERC_CHANGE values in it too.

Question: How to include other wanted columns' values inside the hovertemplate? Specifically, How do I include PERC_CHANGE values as I shown desired output below:

desired hover template output

I solved my specific problem, check pic below (adding 3rd element it is, please see comments), however question remains the same as I do not see how to do this for 4th, 5th and so on elements. enter image description here


Solution

  • For Plotly Express, you need to use the custom_data argument when you create the figure. For example:

    fig = px.scatter(
        data_frame=df, 
        x='ColX', 
        y='ColY', 
        custom_data=['Col1', 'Col2', 'Col3']
    )
    

    and then modify it using update_traces and hovertemplate, referencing it as customdata. For example:

    fig.update_traces(
        hovertemplate="<br>".join([
            "ColX: %{x}",
            "ColY: %{y}",
            "Col1: %{customdata[0]}",
            "Col2: %{customdata[1]}",
            "Col3: %{customdata[2]}",
        ])
    )
    

    This took a lot of trial and error to figure out, as it isn't well-documented, and the inconsistency between the custom_data and customdata is confusing.