Plotly:如何将工具提示添加到散点图以获得额外的变量?

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

我有以下数据框,我想将其呈现在 x 和 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

当我将鼠标悬停在方块上时,我希望有一个工具提示在文本字段中显示我的 z 值。为此,我使用 plotly。这是我的代码:

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()

是否可以在绘图中将 z 作为工具提示显示?它对我不起作用。

只需在 hovertemplate 中包含 '%{text}' 并将 ['z {}'.format(i) for i in data['z']] 分配给 go.Scatter() 中的 text 即可得到:

完整代码:

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()