先貼圖

image.png
需求是顯示三個獨(dú)立的圖表,在其中一個顯示tooltip時其他圖表的信息同時顯示。
一、思路:在echarts里并沒有提供不同繪制區(qū)域同時顯示圖表tooltip的方法,那就只能將這幾個圖表繪制在同一的區(qū)域里面
二、方法:配置3個網(wǎng)格布局
// 配置3個網(wǎng)格布局
const gridWidth = 27; // 每個圖表占27%寬度
const grids = [];
for (let i = 0; i < 3; i++) {
grids.push({
left: i === 0 ? '5%' : i === 1 ? `38%` : '70%',
width: `${gridWidth}%`,
top: '1%',
height: '92%',
bottom: '0%'
});
}
填充圖表數(shù)據(jù)及圖表所使用的網(wǎng)格信息
const series = [];
for (let index = 0; index < 3; index++) {
series.push({
name: '',
type: 'line',
xAxisIndex: index,
yAxisIndex: index,
data: [],
symbol: 'none',
lineStyle: {
width: 2,
color: '#91cc75',
},
animation: false, // 關(guān)閉動畫以提高性能
smooth: false, // 不使用平滑曲線
});
}
配置各個網(wǎng)格的XY軸信息
// 配置X軸(數(shù)值軸)
const xAxes = [];
for (let i = 0; i < 3; i++) {
xAxes.push({
type: 'value',
gridIndex: i,
axisLine: {
onZero: false // 解決反轉(zhuǎn)Y軸后X軸回跑到頂部的問題
}
});
}
// 配置Y軸(時間軸)
const yAxes = [];
for (let i = 0; i < 3; i++) {
yAxes.push({
type: 'value',
gridIndex: i,
inverse: true, // 從上往下顯示
});
}
配置option
const option = {
tooltip: {
trigger: 'axis', //橫向顯示tooltip
axisPointer: { //線的樣式
type: 'line',
axis: 'y',
lineStyle: {
type: 'solid',
color: 'red',
},
},
formatter(params: any) {
if (!params || params.length === 0) {
return '';
}
let result = ''
for (let index = 0; index < params.length; index++) {
const item = params[index]
result += `<div style="font-weight:600;margin-bottom:6px;"> ${item.seriesName}:${item.value[1]}</div>`;
}
return result
},
},
axisPointer: {
link: [
{
yAxisIndex: [0, 1, 2] // 三條線同時顯示
}
],
},
grid: grids,
xAxis: xAxes,
yAxis: yAxes,
series,
};