将工具提示添加到散点图中

问题描述 投票:1回答:1

我有以下数据框,要在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作为工具提示?它对我不起作用。

pandas matplotlib plotly scatter mousehover
1个回答
0
投票

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

enter image description here

完整代码:

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()
© www.soinside.com 2019 - 2024. All rights reserved.