Search code examples
angularjsangularjs-nvd3-directives

How to get the right custom color for legend


Custom colours for doughnut chart is not showing in legend, rather legends take arbitrary colours. How can I make it pickup those custom colours?

app.controller("ExampleController", ["$scope", function ($scope) {
        $scope.pie = [
            {key: "Passed", y: 2},
            {key: "Failed", y: 3}
        ];

        var colorArray = ['red', 'green'];
        $scope.colorFunction = function() {
            return function(d, i) {
                return colorArray[i];
            };
        };
        ...x y functions ...
}]);

HTML

...
    <nvd3-pie-chart
            data="pie"
            id="donutLabelsOutsideExample"
            width="450"
            height="350"
            x="xFunction()"
            y="yFunction()"
            donut="true"
            showLabels="true"
            showLegend="true"
            donutLabelsOutside="true"
            labelType="percent"
            color="colorFunction()">
        <svg height="250"></svg>
    </nvd3-pie-chart>
...

Legend screenshot


Solution

  • The source code for the pie chart contains an attribute for legendcolor, so you can try adding that attribute.

    legendcolor="colorFunction()"
    

    Why it works:

    1. In the controller of pieChart there is a call to checkElementID which in turn calls configureLegend
    2. configureLegend is found in source code and has the following code

    chart.legend.color(attrs.legendcolor === undefined ? nv.utils.defaultColor() : scope.legendcolor());

    attrs.legendcolor is pulled from your directive attribute.