为折线图上的每个点添加文本作为工具提示

时间:2016-12-13 23:13:33

标签: javascript chart.js

我想知道ChartJS中是否有一个选项,如果我将鼠标悬停在折线图上的单个点上,我将如何看到额外的信息。目前我的数据如下:

function drawChart(dataSets) {
    Chart.defaults.global.maintainAspectRatio = false;
    Chart.defaults.global.responsive = false;
    var data = {
        labels: ["ID"]
        , datasets: dataSets
    };
    var options = {
        title: {
            display: true
            , text: 'Custom Chart Title'
        }
        , scales: {
            yAxes: [{
                ticks: {
                    beginAtZero: true
                }
            }]
            , xAxes: [{
                type: "linear"
                , position: "bottom"
            }]
        }
        , tooltips: {
            callbacks: {
                label: function (tooltipItem, data) {
                    alert("Entered tooltip callback.");
                    return i18n.t('chart.count') + ': ' + getCount(tooltipItem, data.datasets);
                }
            }
        }
    };
    var myChart = Chart.Line(ctx, {
        data: data
        , options: options
    });
}

function getCount(tooltipItem, datasets) {
    return datasets[tooltipItem.datasetIndex].data.find(datum => {
        return datum.x === tooltipItem.xLabel && datum.y === tooltipItem.yLabel;
    }).count;
}

这就是一个数据点的样子:

x:5
, y:5
, count:2

但是alert"输入的工具提示"从来没有被叫过,我做错了什么?相反,我在我的控制台(谷歌浏览器)上收到此错误:

enter image description here

2 个答案:

答案 0 :(得分:1)

看起来像这样:

label: sensorID,
data: [0,1,2,3],
backgroundColor: [
        'rgba(' + rndColor() + ',' + rndColor() + ',' + rndColor() + ',0.2)'
],
borderColor: [
        'rgba(' + rndColor() + ',' + rndColor() + ',' + rndColor() + ',0.2)'
],
options: {
    tooltips: {
        enabled: true
        custom: function(tooltip) {
            // code here to customize a tooltip
        }
    }
}

http://www.chartjs.org/docs/#chart-configuration-tooltip-configuration

http://www.chartjs.org/docs/#advanced-usage-external-tooltips

  

有关如何获取的示例,请参阅sample / line-customTooltips.html   启动。

答案 1 :(得分:1)

我添加自定义工具提示的方式。     首先,我创建了一个数据集,其中数据数组我添加了其他信息,如“count”

x: 10,
y: 12,
count: 2

除非我在工具提示下的选项挂钩中手动获取,否则此计数不会显示在图表中。

tooltips: {
      callbacks: {
                label: function(tooltipItem, data) {
                    return i18n.t('chart.count') +': ' + getCount(tooltipItem, data.datasets);
                }
      }
 }

获取未在图表

中显示的给定数据集的计数
function getCount(tooltipItem, datasets) {
    return datasets[tooltipItem.datasetIndex].data.find(datum => {
        return datum.x === tooltipItem.xLabel && datum.y === tooltipItem.yLabel;
    }).count;
}

结果:   enter image description here 编辑:添加我的数据集的示例

return [{
    label: 'Example dataset',
    backgroundColor: '#98cc99',
    borderColor: '#98cc99',
    pointHoverRadius: 3,
    data: [ {x:1,y:2,count:3}, {x:2,y3,count:4}, ...]
}];
相关问题