Search code examples
javascriptd3.jschartspie-chart

D3 pie chart rendering in only one color


I am building a pie chart using the D3 library. Everything is going smoothly except for the colours. Data are stored in the normal Object format.

I defined colour variable as :

    var color = d3.scaleOrdinal()
            .range(d3.schemeCategory10);

and my enter selection binding code is:

        var g = svg.selectAll("path")
              .data(pieArcs, keyField)
              .style("fill", function(d) { return color(d.data.key); });

        var g2 = g
            .enter()
            .append("path")
            .each(function(d) { this.dPrevious = d; })
            .style("fill", function(d) { return color(d.data.key); })
            .attr('fill', d => color(d.data.key))

Changed every aspect, checked all D3 pie charts examples, reached the bottom of the internet, but only getting this (everything else is working):

pie chart

All I need is to have every arc distinguished in different color.


Solution

  • As @adelriosantiago indicated d.data.key was not working. I have finally colored the piechart using attr

    .attr("fill", d => color(keyFieldFunction(d.data)));
    

    when the keyFieldFunction was defined back in the code as:

    var GUPkeyField = function(d){return d.data.key};
    

    colored pie chart