Highcharts - 当数据是动态时,将颜色指定给特定值

时间:2014-01-21 16:10:32

标签: javascript jquery rest highcharts sharepoint-2013

**注意:基于内部的项目

我正在开发的项目利用HighCharts生成饼图。通过使用REST API查询SharePoint列表,可以动态创建此饼图的数据。我们总共有9个图表以这种方式创建,其中8个图表有一个过滤器应用于将结果缩小到特定组而不是整体。问题是切片的颜色不一致,因为每次查询数据并将数据组装到dataArray中时,值的顺序不同。我们想要尝试做的是为每个数据点值指定一种颜色,以使颜色保持一致。

例如:

Resource = #123ABC
Lost Resource = #456DEF
User Error = #789GHI

然后我们需要循环遍历DataArray,并将这些值应用于该饼图切片(如果该切片存在于该数据集中)。我们的数据集例如:

[Resource, 81.6],[Lost Resource, 1.0],[User Error, 0.01]

同样,我们的数据是动态的,所以我们的实际系列代码是:

series: [{
            type: 'pie',
            name: chartTitle,
            data: countArray,
        }]

以下是我们正在使用的完整代码:

Utility.js文件(将数据处理为countArray)

"use strict";

var EngagementChartBuilder = window.EngagementChartBuilder || {};

EngagementChartBuilder.Utilities = function () {
var buildCategoryCounts = function (countArray, dataArray) {
    if (countArray == undefined) {
        countArray = [];
    }

    for (var i = 0; i < dataArray.length; i++) {
        var currValue = parseInt(dataArray[i].hours);
        var currName = dataArray[i].reason;
        var found = false;
        for (var j = 0; j < countArray.length; j++) {
            if (countArray[j][0] == currName) {
                found = true;
                var newCount = countArray[j][1];
                countArray[j][1] = newCount + currValue;
            }
        }
        if (!found) {
            countArray.push([currName, currValue]);
        }
    }

    return countArray;
},

loadPieChart = function (countArray, colorArray, divId, chartTitle) {
    //Build Pie Chart
    Highcharts.setOptions({
    })
    $(divId).highcharts({
        chart: {
            plotBackgroundColor: null,
            plotBorderWidth: null,
            plotShadow: false,
            backgroundColor:'rgba(255, 255, 255, 0.1)'
        },
        credits: {
            enabled: false
        },
        colors: colorArray,

        legend: {
            layout: 'horizontal',
        },
        title: {
            text: chartTitle
        },
        tooltip: {
            pointFormat: '<b>{point.y} hours</b>',
            percentageDecimals: 0
        },
        plotOptions: {
            pie: {
                allowPointSelect: true,
                cursor: 'pointer',
                dataLabels: {
                    enabled: true,
                    color: '#000000',
                    connectorColor: '#000000',
                    format: '<b>{point.name}</b> {point.percentage:.1f} %'
                },
                showInLegend: true
            }
        },
        series: [{
            type: 'pie',
            name: chartTitle,
            data: countArray,
        }]
    });
}   

ViewModel.js REST QUERY

if (!Array.prototype.filter) {
Array.prototype.filter = function (fun /*, thisp */) {
    "use strict";

    if (this == null)
        throw new TypeError();

    var t = Object(this);
    var len = t.length >>> 0;
    if (typeof fun != "function")
        throw new TypeError();

    var res = [];
    var thisp = arguments[1];
    for (var i = 0; i < len; i++) {
        if (i in t) {
            var val = t[i]; // in case fun mutates this
            if (fun.call(thisp, val, i, t))
                res.push(val);
        }
    }

    return res;
};
}

"use strict";

var EngagementChartBuilder = window.EngagementChartBuilder || {};

EngagementChartBuilder.EngagementsPieChart_COR = function () {
var load = function () {
    $.when(
        //Empire Engagements List
        EngagementChartBuilder.RESTQuery.execute("QA_TimeMgtPerRelease", "$select=*,ProjectRelease/CALCReportGroup,Reason_x0020_Type,CalculatedSubtotal&$filter=(((Reason_x0020_Type%20ne%20'Weekend%20Hours')%20and%20(Reason_x0020_Type%20ne%20'After%20Hours'))%20and%20(ProjectRelease/CALCReportGroup%20eq%20'COR'))&$top=2000")
    ).done(
        function (engagements1) {
            var dataArray = [];
            var countArray = [];

            //Get data from Empire Engagements List
            var results = engagements1.d.results;
            var filtered = [];
            for (var i = 0; i < results.length; i++) {
                if (results[i].ProjectRelease/CALCReportGroup == 'COR') {
                    filtered.push(results[i]);
                }
            }
            for (var i = 0; i < filtered.length; i++) {
                var reason = filtered[i].Reason_x0020_Type;
                var hours = filtered[i].CalculatedSubtotal;
                dataArray[i] = { 'hours': hours, 'reason': reason };
            }

            countArray = EngagementChartBuilder.Utilities.buildCategoryCounts(countArray, dataArray);

            //Build Chart
            EngagementChartBuilder.Utilities.loadPieChart CountArray, "#engagementPieChart_COR", "Testing Time vs. Time Lost (COR)");
        }
    ).fail(
        function (engagements1) {
            $("#engagementPieChart_COR").html("<strong>An error has occurred.</strong>");
        }
    );
};

return {
    load: load
}
}();    

1 个答案:

答案 0 :(得分:0)

不使用数组作为点,而是将对象用作点,简单的更改:

countArray.push([currName, currValue]);

为:

countArray.push({ name: currName, y: currValue, color: 'red' });

第二次改变:

var newCount = countArray[j][1];
countArray[j][1] = newCount + currValue;

为:

var newCount = countArray[j].y;
countArray[j].y = newCount + currValue;