[Chartjs]-Is it possible to reverse the display order of segments in polar chart?

0đź‘Ť

I figured out a way to extend the PolarArea chart to generate the result I need. It’s not actually going counter-clockwise, but for my current purposes it’s working.

Here’s the part of the PolarArea chart that draws the chart:

        draw : function(ease){
        var easingDecimal = ease || 1;
        //Clear & draw the canvas
        this.clear();
        helpers.each(this.segments,function(segment, index){
            segment.transition({
                circumference : this.scale.getCircumference(),
                outerRadius : this.scale.calculateCenterOffset(segment.value)
            },easingDecimal);

            segment.endAngle = segment.startAngle + segment.circumference;

            // If we've removed the first segment we need to set the first one to
            // start at the top.
            if (index === 0){
                segment.startAngle = this.options.startAngle; //Math.PI * 1.5;
            }

            //Check to see if it's the last segment, if not get the next and update the start angle
            if (index < this.segments.length - 1){
                this.segments[index+1].startAngle = segment.endAngle;
            }
            segment.draw();
        }, this);
        this.scale.draw();
    }

So, after thinking it through a bit, and some trial & error, I just changed this:

this.segments[index+1].startAngle = segment.endAngle;

to this:

this.segments[index+1].startAngle = segment.endAngle + segment.circumference;

So while it still draws the segments in clockwise order, it “skips” a “segment space” before drawing each segment after the first one. With three segments, the result is draw data point 1 in segment 1, skip segment 2, draw data point 2 in segment 3, skip segment 1, draw data point 3 in segment 2.

Not exactly elegant… and it won’t work with any other number of data points (odd numbers of data points will produce the graphic, but the segments’ order will be off)… but it solves my immediate challenge.

0đź‘Ť

Why not reverse the data array?

// sort by smallest first
myArray.sort(function(a,b) {
    return a.value - b.value;
});

// draw Chart
new Chart(ctx).Pie(myArray, options);

Leave a comment