javascript - 如何获取点击的条形图工具提示数据?

标签 javascript chart.js

我有一个条形图,单击任何条形图时,数据都会显示在工具提示中。我需要 onClick 函数中的工具提示数据。

以下是我的条形图代码:

var tool = new Chart(canvas, {
    type: 'bar',
    data: data,
    options: {
        legend: {
            display: true,
            labels: {
                fontColor: 'rgb(255, 99, 132)'
            },
            position : 'bottom'
        },
        title: {
            display: true,
            text: title 
        },
        scales: {
            xAxes: [{stacked: true,barPercentage: 5.0,
                categoryPercentage: 0.2}],
                yAxes: [{
                    stacked: true,
                    ticks: {
                        beginAtZero: true 
                    },
                    barPercentage: 0.3
                }]
        },
        events: [ "click"],
        onClick: function(event, array){

            console.log("tool.data:",tool.tooltip);

        }

    }
});

enter image description here

我想要点击函数中的数据,例如“missed”、“medium”、78。

最佳答案

您可以使用以下onClick函数来获取工具提示数据:

onClick: function(event, element) {
   var activeElement = element[0];
   var data = activeElement._chart.data;
   var barIndex = activeElement._index;
   var datasetIndex = activeElement._datasetIndex;

   var datasetLabel = data.datasets[datasetIndex].label;
   var xLabel = data.labels[barIndex];
   var yLabel = data.datasets[datasetIndex].data[barIndex];

   console.log(datasetLabel, xLabel, yLabel);
}

此外,您还需要将图表的悬停模式设置为最近才能使其正常工作:

hover: {
   mode: 'nearest'
}

查看working example .

关于javascript - 如何获取点击的条形图工具提示数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47075025/

相关文章:

javascript - Cookie 未使用 jquery 正确删除

php - 如何在 PHP 中接收 JSON 对象?

javascript - 转发 Promise 导致 Promise 链 - 为什么我得到 Promise 对象而不是拒绝值

javascript - 如何通过 Web 应用程序中的值从 firebase 数据库检索数据?

laravel - 在 Laravel 5.1 中实现 Charts.js

javascript - 如何根据来自 REST 调用的响应形成 json 数组?

javascript - Chart.js 子标签

javascript - myDoughnut 动画上的 setInterval

angularjs - 如何定义 chart.js 时间刻度日期格式

python - 图表js条形图上方的空间