How to selecting columns in dataframe for hovertemplate?

Hi there!

I wish to have a hovertemplate where I can select different columns of my dataframe.

I wrote a function to create a trace line for several subplots.

def add_trace_line(figure_object, df, x, y, row_nr, col_nr, scattertype, line_color, width, name, opacity=1):

      _height = df['height']
      _thickness1 = df['thickness_1']
      _thickness2 = df['thickness_2']

      _hovertemplate = ('<i>Value</i>: %{y:.2f}'+
                      '<br><b>Height</b>: %{_height}<br>'+
                      '<br><b>Thickness 1</b>: %{_thickness1}<br>'+
                      '<br><b>Thickness 2</b>: %{_thickness2}<br>'+
                      '<br><b>KM</b>: %{x}<br>')

      if scattertype == 'line':
        if row_nr != 0:
            return figure_object.add_trace(go.Scatter(x=x,
                                                      hovertemplate = _hovertemplate,
                                                      ), row=row_nr, col=col_nr)

However, this does not work.

Hence, how can I select multiple columns of my dataframe and show them when hovering?

Thank you in advance!

Hi @NielsHoogeveen, welcome to the forum! Your function does not work because you need to pass to plotly the data which will appear in the hover. The hovertemplate is just a formatted string. You can add customdata to the go.Scatter trace as described in, or use px.scatter from, in which case the syntax would be

px.scatter(df, x=x, y=y, hover_data=['height', 'thickness_1', 'thickness_2'])

Note that you can modify the hovertemplate generated by using fig.update_traces.

Hi @NielsHoogeveen,

To get a working definition of customdata from three dataframe columns, insert in your trace definition:

customdata  = np.stack((df['height'], df['thickness_1'], df['thickness_2']), axis=-1)

hovertemplate = ('<i>Value</i>: %{y:.2f}'+\
                      '<br><b>Height</b>: %{customdata[0]}<br>'+\
                      '<br><b>Thickness 1</b>: %{customdata[1]}<br>'+\
                      '<br><b>Thickness 2</b>: %{customdata[2]}<br>'+\
                      '<br><b>KM</b>: %{x}<br>')

For more details see this tutorial: