我正在尝试通过JavaScript访问当前悬停的系列数据和颜色。数据可用于图例和工具提示,但我不确定如何直接访问它。
可以将图例放在外部容器中,但是它们的代码会创建许多额外的容器/包装器,这使得格式化变得困难。 This Github question解决了这个问题,但未提供答案。
也许事件可以用来检测图例文本或tspan元素的变化,然后获取新文本,但我不知道如何做到这一点(使用amCharts事件)以及效率如何(特别是对于多个系列和/或带有同步游标的图表)。
Another idea是根据光标位置获取数据,但这似乎效率低下(cursorpositionchanged
过于频繁地触发 - 即使系列数据没有改变,鼠标/光标移动也是如此)。也许根据dateAxis值的变化可以更有效地完成它?例如,使用positionchanged
事件侦听器:
chart.cursor.lineX.events.on('positionchanged', function() {
// get series data and do something with it
});
至少在使用chart.cursor.xAxis = dateAxis
时,positionchanged
事件似乎只在光标跳转到新值时触发。因此,它比触发鼠标/光标移动的事件更有效。
任何建议,将不胜感激。
UPDATE
目前徘徊,我指的是通过工具提示(例如)用鼠标悬停在图表上的系列数据和颜色。
您可以尝试的一种方法是在关注对象上为adapter设置tooltipText
。由于这可能会多次运行,特别是通过图表光标,因此可能通过监视唯一值来跟踪工具提示的变化,例如:在提供的样本中,这将是date
字段。您正在寻找的数据可以在适配器的target.tooltipDataItem
中找到。如果在系列中,颜色将是target.tooltipDataItem.component.fill
(在线系列示例的情况下,target
是线系列并且没有颜色变化,因此您可以使用target.fill
),否则例如,在CandleStick系列的情况下,颜色将在蜡烛棒上,或column
,即通过target.tooltipDataItem.column.fill
。
LineSeries的示例适配器:
var tooltipDate;
series.adapter.add("tooltipText", function(text, target) {
// data via target.tooltipDataItem.dataContext
console.log('text adapter; color: ', target.tooltipDataItem.component.fill.hex);
if (tooltipDate !== target.tooltipDataItem.dataContext.date) {
console.log('new tooltip date, do something');
tooltipDate = target.tooltipDataItem.dataContext.date;
}
// note: in this case: component === target
return text;
});
演示:
https://codepen.io/team/amcharts/pen/9f621f6a0e5d0441fe55b99a25094e2b
样品烛台系列适配器:
var tooltipDate;
series.adapter.add("tooltipText", function(text, target) {
// data via target.tooltipDataItem.dataContext
console.log('text adapter; color: ', target.tooltipDataItem.column.fill.hex);
if (tooltipDate !== target.tooltipDataItem.dataContext.date) {
console.log('new tooltip date, do something');
tooltipDate = target.tooltipDataItem.dataContext.date;
}
return text;
});
演示:
https://codepen.io/team/amcharts/pen/80343b59241b72cf8246c266d70281a7
让我们知道这是否有意义,并且如果适配器路由是捕获更改,数据,颜色的好时间点,以及它是否足够有效,可以采用这种方式。