JustAMartin
JustAMartin

Reputation: 13733

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

There have been a few answers on StackOverflow with suggestions for how to rotate the pie chart using a fixed value and rotation option of Chart.js, but I haven't yet found how to create a rotation formula that accounts for actual data values and rotates the chart so that its sectors are always aligned on horizontal axis.

An example:

https://i.sstatic.net/JSrTR.png

(could not embed the image here; SO keeps saying it cannot connect to Imgur).

Is there any Chart.js option to align the pie sector center axis or do I have to calculate the rotation myself?

For example, with data values [5,10] I can achieve the required rotation with formula rotation: 120/180 * Math.PI, but I'm not sure how to make the formula work for dynamic values.

Upvotes: 0

Views: 539

Answers (1)

JustAMartin
JustAMartin

Reputation: 13733

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

Upvotes: 1

Related Questions