概要
由于 hovertemplate
不支持直接进行复杂的字符串操作,所以可以对需要展示的数据进行预处理。
基本步骤:
1. 数据预处理:例如我这里想鼠标移入时展示的数据是name和一个数值
for (let i = 1; i < data.length - 1; i++) {
scatterHoverData.push({
name: data[i][0],
thick: thick
})
}
2.将预处理好的数据进行传递
其中需要注意的是需要进行展示的数据一定要放在customdata中,并且是一个数组,其长度和x,y的一致。这样占位符%{customdata.name}、 %{customdata.thick}才会生效。
const trace2 = {
x: scatterData.x,
y: scatterData.y,
text: scatterData.text,
customdata: scatterData.scatterHoverData,
mode: 'markers+text',
type: 'scatter',
textposition: 'bottom center',
hovertemplate: '<b>%{customdata.name}: %{customdata.thick}</b><br>' +
'<b>坐标: (%{x}, %{y})</b><br>' +
'<extra></extra>',
hoveron: 'points',
};
const layout = {};
Plotly.newPlot(`canvas${ name }`,
[trace, trace2],
layout,
{
scrollZoom: true,
locale: 'zh-cn',
hovermode: 'closest',
displayModeBar: true, // 显示工具栏
displaylogo: false, // 隐藏logo
responsive: true, // 窗口响应式
}
);
3.其他常用占位符
%{x}
:插入数据点的 x 值。%{y}
:插入数据点的 y 值。%{z}
:插入数据点的 z 值(适用于 3D 图表)。%{text}
:插入数据点的自定义文