Python/Plotly: How to customize hover-template on with what information to show?

32,155

Solution 1

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.

Solution 2

You can add custom data to hovertemplate as :

hovertemplate = 'Price: $%{customdata[0]:.2f}'+'<br>Week: %{customdata[1]} ' 
+ '<br>Change: %{customdata[2]}'

where customdata can either be your group_dfff or even some other totally different data frame from which you want to fetch data for your hover info.

Here is the link to the documentation on plotly.

Solution 3

I've actually had the similar problem, and trust me it took me 2 and a half hour to figure out. Let's understand with an example.

fig = make_subplots(rows=1,cols=2,subplot_titles=('First plot','Second plot'),
                   specs=[[{'type': 'scene'}, {'type': 'scene'}]])

fig.add_trace(go.Scatter3d(x=[0,1,2,3],y=[0,1,2,3],z=[0,1,2,3]), row=1,col=1)
fig.add_trace(go.Scatter3d(x=[0,1,2,3],y=[0,1,2,3], z=[0,1,2,3]), row=1,col=2)

fig.update_layout(title='Add Custom Data')

fig.show()

This will create simple two scatter3d plots, where hoverdata is x,y and z axis. Now you want to add the data m=[9,8,7,6,5] to first plot. you can parse m in text argument and add hovertemplate as well.

fig.add_trace(go.Scatter3d(x=[0,1,2,3],y=[0,1,2,3],z=[0,1,2,3],
                          text=[9,8,7,6], hovertemplate='<br>x:%{x}<br>y:%{y}<br>z:%{z}<br>m:%{text}'), row=1,col=1)

This should work just fine. But now we want to add one more list say n=[5,6,7,8] to the first plot (or any). We will use customdata argument this time.

fig.add_trace(go.Scatter3d(x=[0,1,2,3],y=[0,1,2,3],z=[0,1,2,3],
                          text=[9,8,7,6],customdata=[5,6,7,8],
                          hovertemplate='<br>x:%{x}<br>y:%{y}<br>z:%{z}<br>m:%{text}<br>n:%{customdata}'), row=1,col=1)

Now what if we want to add our 3rd list of custom data. Here comes the tricky part. You cannot parse the list of two lists in the custom data, and then call customdata[0] and customdata[1], it's not that simple. our 3rd list is k=[2,4,6,8].

We need customdata=[[[5],[2]],[[6],[4]],[[7],[6]],[[8],[8]]] like this and it should work fine. Basically we need to give plotly a single list (or array) where in each element it's the list of all points you want to show.

fig.add_trace(go.Scatter3d(x=[0,1,2,3],y=[0,1,2,3],z=[0,1,2,3],
                          text=[9,8,7,6],customdata=[[[5],[2]],
                                                     [[6],[4]],
                                                     [[7],[6]],
                                                     [[8],[8]]],
                          hovertemplate='<br>x:%{x}<br>y:%{y}<br>z:%{z}<br>m:%{text}<br>n:%{customdata[0]}<br>k:%{customdata[1]}'), row=1,col=1)

We almost done, but there is one thing left. It's lots of work to manually create list like we given in customdata, therefore we'll automate it using powerful library import numpy as np

n = [5,6,7,8]
k = [2,4,6,8]

nk = np.empty(shape=(4,2,1), dtype='object')
nk[:,0] = np.array(n).reshape(-1,1)
nk[:,1] = np.array(k).reshape(-1,1)
fig.add_trace(go.Scatter3d(x=[0,1,2,3],y=[0,1,2,3],z=[0,1,2,3],
                          text=[9,8,7,6],customdata=nk,
                          hovertemplate='<br>x:%{x}<br>y:%{y}<br>z:%{z}<br>m:%{text}<br>n:%{customdata[0]}<br>k:%{customdata[1]}'), row=1,col=1)

BOOM ! You can parse df['Column name'] in place of np.array(n) if you want to add data directly from dataframe.

Share:
32,155
DGomonov
Author by

DGomonov

Interested in Machine &amp; Deep Learning

Updated on July 09, 2022

Comments

  • DGomonov
    DGomonov almost 2 years

    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

    Help is really appreciated!