在条形图js报告中,跳过了零值,因此条形无效

时间:2018-10-29 13:40:14

标签: chart.js

我堆叠了带有2种投票类型(正确/不正确)值的栏(Chart.js版本:2.7.2)。 可以正常工作,除非有一些关于正确投票的数据而没有关于非正确投票的数据的情况。反之亦然
为了解决这个问题,我在服务器上添加了一些检查,对于不存在的值,我在count字段的0值中添加了行,因此数据集看起来像

请注意,对于id为“:4,” vote_name“:”哪个虚构的城市是蝙蝠侠的故乡?“的voitItemUsersResultsNoneCorrect数组行 字段计数值为0。查看生成的条形图,我看到跳过了0值,并使用FROM NEXT行的值来构建图表,因此所有下一个条形 无效。

{"error_code":0,"message":"",
    "voteItemUsersResultsCorrect":{"0":
        {"count":9,"id":12,"vote_name":"According to the old proverb, to which European capital city do all roads lead ?"},"1":
        {"count":6,"id":13,"vote_name":"On which mountain did Moses receive the Ten Commandments ?"},"2":
        {"count":10,"id":9,"vote_name":"Traditionally, how many Wonders of the World are there ?"},"3":
        {"count":6,"id":10,"vote_name":"What is the name of the fairy in Peter Pan ?"},"4":
        {"count":12,"id":8,"vote_name":"Which crime-fighting cartoon dog has the initals \u201cS.D.\u201d on his collar ?"},"5":
        {"count":16,"id":4,"vote_name":"Which fictional city is the home of Batman ?"},"6":
        {"count":5,"id":14,"vote_name":"Which is the tallest mammal?"},"7":
        {"count":8,"id":11,"vote_name":"Which planet is the closest to Earth ?"},"10":
        {"count":0,"id":2,"vote_name":"Who Framed Roger Rabbit ?"},"8":
        {"count":8,"id":15,"vote_name":"Who directed the movie Jaws?"},"9":
        {"count":8,"id":5,"vote_name":"Who was known as the Maid of Orleans ?"}},

    "voteItemUsersResultsNoneCorrect":{"0":
        {"count":22,"id":12,"vote_name":"According to the old proverb, to which European capital city do all roads lead ?"},"1":
        {"count":25,"id":13,"vote_name":"On which mountain did Moses receive the Ten Commandments ?"},"2":
        {"count":21,"id":9,"vote_name":"Traditionally, how many Wonders of the World are there ?"},"3":
        {"count":25,"id":10,"vote_name":"What is the name of the fairy in Peter Pan ?"},"4":
        {"count":19,"id":8,"vote_name":"Which crime-fighting cartoon dog has the initals \u201cS.D.\u201d on his collar ?"},"10":
        {"count":0,"id":4,"vote_name":"Which fictional city is the home of Batman ?"},"5":
        {"count":26,"id":14,"vote_name":"Which is the tallest mammal?"},"6":
        {"count":23,"id":11,"vote_name":"Which planet is the closest to Earth ?"},"8":
        {"count":27,"id":2,"vote_name":"Who Framed Roger Rabbit ?"},"7":
        {"count":23,"id":15,"vote_name":"Who directed the movie Jaws?"},"9":
        {"count":23,"id":5,"vote_name":"Who was known as the Maid of Orleans ?"}
    }
}

我展示了数据的完全检索和设置栏选项, 首先,我必须为3个数组monthsXCoordItems,voteNamelabels,voteValuesCorrect设置值,并在其上创建条形图。

$.ajax({
    url: href,
    type: "POST",
    dataType: "json",
    data: dataArray,
}).done(function (response) {
    if (response.error_code == 0) {

        this.this_voteItemUsersResultsCorrect = response.voteItemUsersResultsCorrect
        this.this_voteItemUsersResultsNoneCorrect = response.voteItemUsersResultsNoneCorrect

        for (var key_index in response.voteItemUsersResultsCorrect) {
            if (response.voteItemUsersResultsCorrect.hasOwnProperty(key_index)) {
                var dataRow= response.voteItemUsersResultsCorrect[key_index];
                monthsXCoordItems.push(dataRow.vote_name);
                voteNamelabels.push(dataRow.vote_name);
                voteValuesCorrect.push(dataRow.count);
            }
        }

        for (var key_index in response.voteItemUsersResultsNoneCorrect) {
            if (response.voteItemUsersResultsNoneCorrect.hasOwnProperty(key_index)) {
                var dataRow= response.voteItemUsersResultsNoneCorrect[key_index];
                voteValuesNoneCorrect.push(dataRow.count);
            }
        }

        var barCanvas = document.getElementById("canvasVoteNames");
        $("#div_canvasVoteNames").css("display","block")

        var barCanvasContext = barCanvas.getContext('2d');

        var numberWithCommas = function (x) {
            return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
        };
        var self = this;
        if (window.chartObject != undefined) { // clear existing instance
            window.chartObject.destroy();
        }
        window.chartObject = new Chart(barCanvasContext, {  
            type: 'bar', // http://www.chartjs.org/docs/latest/charts/bar.html
            data: {
                labels: monthsXCoordItems,
                datasets: [{
                    label: 'Correct Votes',
                    data: voteValuesCorrect,
                }, {
                    label: 'Incorrect Votes',
                    data: voteValuesNoneCorrect,
                }
            ]
        },

        options: { // options of Report By Vote Names
            animation: {
                duration: 10,
            },

            scales: { // options for x and y scales
                xAxes: [{
                    stacked: true,    
                    gridLines: {
                        display: true,
                        // offsetGridLines: true,
                    },
                    // barThickness: 70,

                }],
                yAxes: [{
                    stacked: true, 
                    ticks: {
                        callback: function (value) { 
                            if (Math.floor(value) === value) {
                                return value;
                            }
                        }, 
                    },
                }],
            }, // scales: { // options for x and y scales
            legend: {display: true}
        }, // options: { // options of Report By Vote Names


        plugins: [{
            beforeInit: function (chart) {
                chart.data.labels.forEach(function (value, index, array) {
                    var a = [];
                    a.push(value.slice(0, this_column_width));
                    var i = 1;
                    while (value.length > (i * this_column_width)) {
                        a.push(value.slice(i * this_column_width, (i + 1) * this_column_width));
                        i++;
                    }
                    array[index] = a;
                })
            }
        }]

    }); 

    barCanvas.onclick = function (e) { 
        var slice = window.chartObject.getElementAtEvent(e);

        if (!slice.length) return; // return if not clicked on slice
        var label = slice[0]._model.label;
        if (label.length > 1) { // that is an array - we need to convert it to string
            var label_text = ''
            for (var key in label) {
                if (label.hasOwnProperty(key)) {
                    label_text = label_text + label[key]
                }
            }
            label = label_text
        }
        self.this_voteItemUsersResultsCorrect.forEach(function (data) {
            if (label == data.vote_name) {
                backendReports.showVoteNamesReportDetailsByVoteId(data.id, data.vote_name)
                return;
            }
        });
    } // barCanvas.onclick = function(e) {
}

if (response.error_code > 0) {
    alertMsg(response.message, 'Reports error!', 'OK', 'fa fa-file-chart-pie')
}
});

有一些想法可以解决此错误吗?

已修改的块#2: 我在线上传了该图表:请打开 http://votes.nilov-sergey-demo-apps.tk/admin/report_votes_by_vote_names 提供了贷方信息,默认情况下将打开包含所有数据的页面,但 “哪个虚构的城市是蝙蝠侠的故乡”,因为它对于不正确的堆栈具有0值,所以无效:https://imgur.com/a/hGfYLog

如果从“航行者”过滤器选择中选择唯一的投票,则可以看到值为0的有效结果:https://imgur.com/a/seshsFp

谢谢!

1 个答案:

答案 0 :(得分:1)

count: 13, id: 4count: 22, id: 2 ...

这意味着,您的脚本将蝙蝠侠与罗杰·兔子混淆了。

可能还有其他错误的值;仅使用0值才最明显。

更好地在服务器端合并数组,以使其易于在图表中使用;这将使索引分配变得更容易-并且还将加快JS的运行时间。与无用的复杂性相比,复杂性通常比无用的复杂性更容易处理(与数组的客户端合并一样)。