Search code examples
javascripthtmlangularjscanvasjs

Pie chart color not changing


I am using a canvasjs to make a pie chart. I am using it in my custom code where I am getting the response from the server in an xml file and then I am using it to fill the chart values. My problem is that I am not able to change the colour of the chart meaning even for different labels the colour remains the same for the whole pie chart.

I used debugger also where it the value for colour is changing but still I am not able to resolve it.

  color: scopes.chart_color_value[i]

I am using an another configuration file where I am storing colour values.

Here is my custom code

$scope.loadChartValue = function (data, scopes) {
    scopes.data_id = [];
    scopes.legend_text = "";
    scopes.inner_chart_data = [];

    for (var i = 0; i <= data.length; i++) {
        var arrayvalue = data[0].data[i]._attr
        if (existsInArray(scopes.data_id, arrayvalue.label._value) == false) {
            scopes.data_id.push(arrayvalue.label._value);
        }
    }
        scopes.inner_chart_data = [];
        var i=1;
        for (var j = 0; j < data[0].data.length; j++) {
            scopes.inner_chart_data.push({ label: data[0].data[j]._attr.label._value, y: data[0].data[j]._attr.value._value });

        scopes.dataset.push(
                   {
                       type: "pie",

                       markerType: "circle",
                       markerSize: scopes.markersize,
                       color: scopes.chart_color_value[i],
                       showInLegend: false,
                       name: scopes.legend_text,
                       dataPoints: scopes.inner_chart_data
                   }
           );
           i++;
        }

}

It is coming like this


Solution

  • It seems you are creating 2 data-series instead of 1 data-series with 2 dataPoints. When color is set at data-series level, whole pie becomes single color, so try changing it at data-point level.

    The following code should work fine.

    for (var j = 0; j < data[0].data.length; j++) {
        scopes.inner_chart_data.push({ label: data[0].data[j]._attr.label._value, y: data[0].data[j]._attr.value._value, color: scopes.chart_color_value[i], });
        i++;
    }
    scopes.dataset.push(
        {
           type: "pie",
           markerType: "circle",
           markerSize: scopes.markersize,                       
           showInLegend: false,
           name: scopes.legend_text,
           dataPoints: scopes.inner_chart_data
        }
    );