Reputation: 485
I have a donut chart showing a number. However is there a way which the donut chart can be out of 100%, so the number I give in the data
section: say 21
, will show 21% complete out of 100?
Image to show desired outcome:
So the donut ring is greyed out and the coloured section is how much has been completed (or what number we allocate to the data
section, I've been looking at the documentation and cannot see a way this can be done?
Code I have currently:
<canvas id="Chart1" style="width=5 height=5"></canvas>
<?php
$var = 3;
?>
var ctx = document.getElementById('Chart1').getContext('2d');
var chart = new Chart(ctx, {
// The type of chart we want to create
type: 'doughnut',
// The data for our dataset
data: {
labels: ['% Complete'],
datasets: [{
label: 'chart1',
backgroundColor: 'rgb(102, 178, 255)',
borderColor: 'rgb(102, 178, 255)',
// Below I just pull out 1 number from the db
data: [<?php echo $var ?>]
}]
},
});
My code outputs the below (so the 3 fills up the whole donut), whereas I would like it show 3% out of 100% complete.
Upvotes: 2
Views: 7541
Reputation: 610
Create a two value dataset, like:
[percent_value, 100-percent_value]
Here's a full demo:
const originalDoughnutDraw = Chart.controllers.doughnut.prototype.draw;
Chart.helpers.extend(Chart.controllers.doughnut.prototype, {
draw: function() {
const chart = this.chart;
const {
width,
height,
ctx,
config
} = chart.chart;
const {
datasets
} = config.data;
const dataset = datasets[0];
const datasetData = dataset.data;
const completed = datasetData[0];
const text = `${completed}% completed`;
let x, y, mid;
originalDoughnutDraw.apply(this, arguments);
const fontSize = (height / 350).toFixed(2);
ctx.font = fontSize + "em Lato, sans-serif";
ctx.textBaseline = "top";
x = Math.round((width - ctx.measureText(text).width) / 2);
y = (height / 1.8) - fontSize;
ctx.fillStyle = "#000000"
ctx.fillText(text, x, y);
mid = x + ctx.measureText(text).width / 2;
}
});
var context = document.getElementById('myChart').getContext('2d');
var percent_value = 3;
var chart = new Chart(context, {
type: 'doughnut',
data: {
labels: ['Completed', 'Pending'],
datasets: [{
label: 'First dataset',
data: [percent_value, 100 - percent_value],
backgroundColor: ['#00baa6', '#ededed']
}]
},
options: {}
});
<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
<canvas id="myChart"></canvas>
Upvotes: 2
Reputation: 20584
Try passing data of [3, 97]. You're trying to use it as a loading indicator but it seems designed for showing 100% of things broken into parts.
If you pass simply [3]
, then that's 100% of your dataset
Upvotes: 3