Chartjs-Rotating a chart.js pie chart with two datapoints to align both sectors on horizontal axis

1👍

Ok, it seems I got it right using a custom formula. Not sure, maybe it could have been done with less effort:

var t1 = 5; // this will come from the server
var t2 = 10; // this will come from the server
var total = t1 + t2; 

// Chart.js draws the first data point from vertical axis
// by default. But if set rotation to 0, it draws at 90 degrees from vertical axis
// (that is - on horizontal axis to the right side).
// Calculating the chart rotation, so that the first sector
// is always facing the left side and is middle-aligned
// on horizontal axis, 
// thus the second sector also will be aligned to the right side.
var percentageOfT1 = t1 / total;
var sectorSizeDeg = 360.0 * percentageOfT1; // circle is 360 degrees 
// thus we can calculate sector degrees easily using the percentage
var halfOffsetDeg = sectorSizeDeg / 2.0;

// rotate 180-halfsector 
// to compensate for horizontal align and reach the middle line of the sector
var finalOffsetDeg = 180.0 - halfOffsetDeg;

...
// in Chart options:
rotation: finalOffsetDeg / 180.0 * Math.PI

Leave a comment