Antv G2 堆叠面积图 Tooltip 总计的实现
Antv G2 V5.2
github能找到这样的历史遗留问题,https://github.com/antvis/G2/issues/3804 不过新版本api有些修改,不能直接使用。
Antv给自己的定义是面粉(在官网评语上写着),并没有提供这些定制功能(不过具体到这个例子,好像echarts也没有直接可用的选项?)。那就只能自己实现了。
方案1:
在图表中同时绘制一根透明的总数的折线图,然后Tooltip就可以自动将其加入了。
// 初始化图表实例
const chart = new G2.Chart({
container: 'container',
autoFit: true,
});
// 声明可视化
chart.data(data)
.area()
.transform([
{ type: 'stackY' }, // Try to remove this line.
])
.encode('x', (d) => new Date(d.date))
.encode('y', 'labors')
.encode('color', 'project')
.encode('shape', 'smooth')
.title({title:"人力面积重叠图"})
.animate({enter:{type:"scaleInY",duration: 1000,delay: 10,}, update: {type: 'morphing',},})
.tooltip({title:(d)=>{return d.date}})
;
chart.line()
.data(totalArr)
.encode('x', (d) => new Date(d.date) )
.encode('y', 'labors')
.encode('shape', 'smooth')
.encode('color', 'project')
.style('stroke', '#ffffff')
.style('lineWidth', 2)
.animate({enter:{type:"scaleInY",duration: 1000,delay: 10,}, update: {type: 'morphing',},})
.tooltip({title:(d)=>{return d.date}}) //两边设置同样的title似乎就会自动合并
;
chart.lineX().data([new Date()]).style('stroke','red').style('strokeWidth', 2).label({text:"Today",dy:-15});
chart.render();
缺点是Total的顺序无法确定,他不一定会被排在哪里,很不方便。
方案2:
chart.interaction('tooltip', {
// render 回调方法返回一个innerHTML 或者 ReactNode
render: (event, { title, items }) =>{
const container = document.createElement("div");
const outer = `<div class="g2-tooltip-title" style="margin-top: 12px;margin-bottom: 12px;">${title}</div>`;
let listItem = "",
count = 0;
for (let i = 0; i < items.length; i++) {
const item = items[i];
if (+item?.value === 0) continue;
count += +item?.value;
listItem += `<li class="g2-tooltip-list-item" data-index={index} style="margin-bottom:4px;display:flex;align-items: center;">
<span class='g2-tooltip-list-item-name'>
<span style="background-color:${item?.mappingData?.color || item?.color};" class="g2-tooltip-list-item-marker"></span>
<span style="margin-right: 16px;" class='g2-tooltip-list-item-name-label'>${item?.name}</span>
</span>
<span class='g2-tooltip-list-item-value' style="display:inline-flex;flex:1;justify-content:space-between">${item?.value}</span>
</li>`;
}
listItem += `<li class="g2-tooltip-list-item" data-index={index} style="margin-bottom:4px;display:flex;align-items: center;">
<span style="background-color: #abe1b1;" class="g2-tooltip-marker"></span>
<span style="display:inline-flex;flex:1;justify-content:space-between">
<span style="margin-right: 16px;">总数:</span><span>${count}</span>
</span>
</li>`;
container.innerHTML = outer +"<ul class='g2-tooltip-list'>"+ listItem +"</ul>";
return container;
},
});
手动拼一个tooltip出来,缺点是写起来十分繁琐

浙公网安备 33010602011771号