I want to create a Doughnut graph with two values. Clicking the graphs should print the value in center. I found a solution in stackoverflow similar to my requirement. I would like to use latest Chart.js library from github. Is this feature is available in latest Chart.js?
To get the label center in donut chart, Select the 2nd pie chart and go to label, Click on automatic next to alignment. Now click on middle under vertical and change the font size as per requirement. Hope this helps you.
Click the chart, and then click the Chart Design tab. Click Add Chart Element > Legend. To change the position of the legend, choose Right, Top, Left, or Bottom. To change the format of the legend, click More Legend Options, and then make the format changes that you want.
It is certainly possible to do something like this in Chart.js v2.x
I think the nicest way to do it is by using a plugin. In fact, Cmyker awnser to the question you linked to even updated his posts to show how this would work in Charts.js v2.x
See his fiddle: https://jsfiddle.net/cmyker/ooxdL2vj/
and the corresponding plugin definition:
Chart.pluginService.register({
beforeDraw: function(chart) {
var width = chart.chart.width,
height = chart.chart.height,
ctx = chart.chart.ctx;
ctx.restore();
var fontSize = (height / 114).toFixed(2);
ctx.font = fontSize + "em sans-serif";
ctx.textBaseline = "middle";
var text = "75%",
textX = Math.round((width - ctx.measureText(text).width) / 2),
textY = height / 2;
ctx.fillText(text, textX, textY);
ctx.save();
}
});
You can also add a parameter to the configuration and use this as text:
"options": {
title: {
display: true,
position: "bottom",
text: 'Upcoming Meetings'
},
legend: {
display: false
},
centertext: "123"
}
And the javascript would look similar to this (please note: doughnuts have a title but no legend, positioning the centered text was somehow experimenting):
<script>
Chart.pluginService.register({
beforeDraw: function (chart) {
if (chart.options.centertext) {
var width = chart.chart.width,
height = chart.chart.height,
ctx = chart.chart.ctx;
ctx.restore();
var fontSize = (height / 80).toFixed(2); // was: 114
ctx.font = fontSize + "em sans-serif";
ctx.textBaseline = "middle";
var text = chart.options.centertext, // "75%",
textX = Math.round((width - ctx.measureText(text).width) / 2),
textY = height / 2 - (chart.titleBlock.height - 15);
ctx.fillText(text, textX, textY);
ctx.save();
}
}
});
</script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With