I am using Chart.js for drawing pie chart in my php page.I found tooltip as showing each slice values.
But I wish to display those values like below image.
I do not know how to do this with chart.js.
Please help me.
My Javascript code:
function drawPie(canvasId,data,legend){
var ctx = $("#pie-canvas-" + canvasId).get(0).getContext("2d");
var piedata = [];
$.each(data,function(i,val){
piedata.push({value:val.count,color:val.color,label:val.status});
});
var options =
{
tooltipTemplate: "<%= Math.round(circumference / 6.283 * 100) %>%",
}
var pie = new Chart(ctx).Pie(piedata,options);
if(legend)document.getElementById("legend").innerHTML = pie.generateLegend();
}
php code:
printf('<table><tr>');
echo '<td style="text-align: right;"><canvas id="pie-canvas-'
. $canvasId
. '" width="256" height="256" ></canvas></td><td style="text-align: left;width:360px;height:auto" id="legend" class="chart-legend"></td></tr></table>';
echo '<script type="text/javascript">drawPie('
. $canvasId
. ', '
. $data3
.', '
. $legend
. ');</script>';
From what I know I don't believe that Chart.JS has any functionality to help for drawing text on a pie chart. But that doesn't mean you can't do it yourself in native JavaScript. I will give you an example on how to do that, below is the code for drawing text for each segment in the pie chart:
A Pie Chart has an array of segments stored in
PieChart.segments
, we can look at thestartAngle
andendAngle
of these segments to determine the angle in between where the text would bemiddleAngle
. Then we would move in that direction byRadius/2
to be in the middle point of the chart in radians.In the example above some other clean-up operations are done, due to the position of text drawn in
fillText()
being the top right corner, we need to get some offset values to correct for that. And finallytextSize
is determined based on the size of the chart itself, the larger the chart the larger the text.Fiddle Example
With some slight modification you can change the discrete number values for a dataset into the percentile numbers in a graph. To do this get the total
value
of the items in your dataset, call thistotalValue
. Then on each segment you can find the percent by doing:The section here
myPieChart.segments[i].value/totalValue
is what calculates the percent that the segment takes up in the chart. For example if the current segment had a value of50
and the totalValue was200
. Then the percent that the segment took up would be:50/200 => 0.25
. The rest is to make this look nice.0.25*100 => 25
, then we add a%
at the end. For whole number percent tiles I rounded to the nearest integer, although can can lead to problems with accuracy. If we need more accuracy you can use.toFixed(n)
to save decimal places. For example we could do this to save a single decimal place when needed:Fiddle Example of percentile with decimals
Fiddle Example of percentile with integers