Search code examples
pythonpandasmatplotlibplotlyscatter

Plotly: How to add tooltip to scatterplot for an extra variable?


I have the following dataframe which i want to present in a scatter plot for x and y:

    x   y   z   M
0   52.8    34.2    94.232224   1.347599
1   48.4    34.2    95.520638   1.410438
2   44.0    34.2    95.688486   1.353541
3   39.6    34.2    93.810213   1.478019
4   35.2    34.2    95.180400   1.163945

When i hover over the squares i want to have a tooltip showing my z value in a textfield. To do this I use plotly. Here is my code:

fig = go.Figure(go.Scatter(mode="markers", x=data['x'], y=data['y'], marker_symbol="square",

                           hovertemplate =
"<b>%{marker.symbol} </b><br><br>" +
    "Z: %{z}<br>",

                           marker_line_color="midnightblue", 
                           marker_color="lightskyblue", 
                           marker_line_width=1, marker_size=5))
fig.show()

Is it possible to show z in the plot as a tooltip? It does not work for me.


Solution

  • Just include '%{text}' in hovertemplate and assign ['z {}'.format(i) for i in data['z']] to text in go.Scatter() to get this:

    enter image description here

    Complete code:

    import plotly.graph_objects as go
    import pandas as pd
    
    data= pd.DataFrame({'x': {0: 52.8, 1: 48.4, 2: 44.0, 3: 39.6, 4: 35.2},
     'y': {0: 34.2, 1: 34.2, 2: 34.2, 3: 34.2, 4: 34.2},
     'z': {0: 94.232224, 1: 95.520638, 2: 95.688486, 3: 93.810213, 4: 95.1804},
     'M': {0: 1.347599,
      1: 1.4104379999999999,
      2: 1.3535409999999999,
      3: 1.478019,
      4: 1.163945}})
    
    fig = go.Figure(go.Scatter(mode="markers", x=data['x'], y=data['y'], marker_symbol="square",
                               hovertemplate = 'y: %{y}'+'<br>x: %{x}<br>'+'%{text}',
                               text = ['z {}'.format(i) for i in data['z']],
                               marker_line_color="midnightblue", 
                               marker_color="lightskyblue", 
                               marker_line_width=1, marker_size=5))
    fig.show()