ChartJs条形图中的可见点总数

时间:2019-10-29 14:31:17

标签: javascript chart.js

chartjs可以通过单击标签来隐藏数据集。我想总结一下条形图的所有要点,但只总结可见的要点。我知道如何总结所有点,但不知道如何检查数据集是否可见。总结一下要点,我使用了onComplete动画事件:

animation: {
    onComplete: function(animation) {
    var sqm = 0;
    this.data.datasets.forEach(function (dataset) {
    dataset.data.forEach(function (points) {
        sqm = sqm + points;
         })
    })
    $("#SquareMeterSurface").val(sqm);
    }
},

这是它的样子:

enter image description here

如何仅对可见数据集求和(在蓝色图中不可见)?我使用ChartJs 2.8

谢谢

1 个答案:

答案 0 :(得分:0)

所以我自己找到了解决方案。传递给onComplete回调的'animation'变量中有一个数组'animation.chart.active',可以循环查找活动数据集索引。仅当将鼠标悬停在图形的条形上方时,才会填充活动数组,这就是为什么仅将鼠标悬停在条形图上才显示点数之和的原因。

整个代码现在看起来像这样:

0.50

和调用.Net Core MVC动作的ajax调用是这样的:

 function success_(data) {
    var ctx = document.getElementById('canvas').getContext('2d');
    window.myBar = new Chart(ctx, {
        type: 'bar',
        data: data,
        options: {
            title: {
                display: true,
                text: 'Square Meters done per day'
            },
            tooltips: {
                mode: 'index',
                intersect: false
            },
            maintainAspectRatio: false,
            responsive: true,
            scales: {
                xAxes: [{
                    stacked: true
                }],
                yAxes: [{
                    stacked: true
                }]
            },
            animation: {
                onComplete: function(animation) {
                    //alert('onAnimationComplete');

                    if (typeof animation.chart !== 'undefined' && typeof animation.chart.active !== 'undefined') {
                        var active_datasets = new Array();
                        //loop through active dataset to get the dataset indexes 
                        //which are visible to the user
                        animation.chart.active.forEach(function(active_ds) {
                            active_datasets.push(active_ds._datasetIndex);
                        })

                        //loop through datasets to get the points for active datasets
                        var sqm = 0;
                        var i = 0;
                        this.data.datasets.forEach(function (dataset) {
                            if (active_datasets.indexOf(i) != -1) {
                                dataset.data.forEach(function (points) {
                                    sqm = sqm + points;
                                })
                            }
                            i = i + 1;
                        })
                        $("#SquareMeterSurface").val(parseFloat(sqm).toFixed(1) + ' m2');
                    }
                }
            },
        }
    });
};