Black Lives Matter. Please consider donating to Black Girls Code today.

Unified hover with extra information for the unified text

Is there a way to neatly add extra information on a mouse hover, however, that also uses an ‘x unified’ method?

For instance, my code is as such.

samp_df = pd.DataFrame({'Date': ['01/03/2020', '02/03/2020', '03/03/2020', '04/03/2020'],
                       'Positive': [5,4,3,5],
                       'Negative': [32,35,17,57],
                       'A': ['AAA', 'BBB', 'CCC', 'DDD'],
                       'B': ['BAB', 'CAC', 'DAD', 'TAT'],
                       'C': ['CAT', 'HAT', 'RAT', 'MAT']})


custom_data = np.stack((samp_df['A'], samp_df['B'], samp_df['C']), axis = -1)

fig = go.Figure()

fig.add_trace(go.Scatter(x = samp_df['Date'], y = samp_df['Positive'], name = 'Positive'))
fig.add_trace(go.Scatter(x = samp_df['Date'], y = samp_df['Negative'], name = 'Negative'))

fig.update_traces(customdata = custom_data, 
                  hovertemplate = "Top 3 Texts: <br> %{customdata[0]} <br> %{customdata[1]} <br> %{customdata[2]}")
fig.update_layout(hovermode='x unified')
fig.show()

However, I’m getting an image like below. What I’d prefer is to have in the hovertext, both the actual numbers of positive and negative, and the three texts but only once and in a neat way, since I know for a fact that it’s the same for both positive and negatve (as per my dataset). Is there a way to do this? I have tried adding the custom data only for the negative portion, but it’s not very neat.

Hi @penatbater,

To insert the info in df[‘Positive’ ] and df[‘Negative’ ] etend the definition of custom_data to:

custom_data = np.stack((samp_df['Positive'],  samp_df['Negative'], samp_df['A'], samp_df['B'], samp_df['C']), axis = -1)

and don’t perform a global trace update, but for each trace, successively:

fig.data[0].update(customdata = custom_data, 
                  hovertemplate = "Top 3 Texts: <br> %{customdata[2]} <br> %{customdata[3]} <br> %{customdata[4]}"+\
                  "<br>y-pos:  %{customdata[0]}"
                  )
fig.data[1].update(customdata = custom_data, 
                  hovertemplate = "Top 3 Texts: <br> %{customdata[2]} <br> %{customdata[3]} <br> %{customdata[4]}"+\
                  "<br>y-neg:  %{customdata[1]}"
                  ) 

or a global update for customdata and particular update (ie each trace update) for hovertemplate.

Oohh thanks! Didn’t know there was an update method!