Display Doughnut Pie Chart As Circle Progress Chart.js - javascript

I want to ask if there is a way to make Pie Chart As Circle Progress with percent value, I want just one slice colored
something like this:
This is my fiddle for now I want just one data.
HTML:
<canvas id="chartProgress" width="300px" height="200"></canvas>
JS:
var chartProgress = document.getElementById("chartProgress");
if (chartProgress) {
var myChartCircle = new Chart(chartProgress, {
type: 'doughnut',
data: {
labels: ["Africa", 'null'],
datasets: [{
label: "Population (millions)",
backgroundColor: ["#5283ff"],
data: [68, 48]
}]
},
plugins: [{
beforeDraw: function(chart) {
var width = chart.chart.width,
height = chart.chart.height,
ctx = chart.chart.ctx;
ctx.restore();
var fontSize = (height / 150).toFixed(2);
ctx.font = fontSize + "em sans-serif";
ctx.fillStyle = "#9b9b9b";
ctx.textBaseline = "middle";
var text = "68%",
textX = Math.round((width - ctx.measureText(text).width) / 2),
textY = height / 2;
ctx.fillText(text, textX, textY);
ctx.save();
}
}],
options: {
legend: {
display: false,
},
responsive: true,
maintainAspectRatio: false,
cutoutPercentage: 85
}
});
}
I know I can do it with normal HTML&CSS or using simple plugin but I want to do it using Chart.js

The Plugin Core API offers different hooks that may be used for executing custom code. You already use the beforeDraw hook to draw text in the middle of the doughnut.
You could now also use the beforeInit hook to modify the chart configuration in order to fit your needs:
beforeInit: (chart) => {
const dataset = chart.data.datasets[0];
chart.data.labels = [dataset.label];
dataset.data = [dataset.percent, 100 - dataset.percent];
}
Given this code, the definition of your dataset would look simple as follows:
{
label: 'Africa / Population (millions)',
percent: 68,
backgroundColor: ['#5283ff']
}
Last you have to define a tooltips.filter, so that the tooltip appears only at the relevant segment.
tooltips: {
filter: tooltipItem => tooltipItem.index == 0
}
Please take a look at your amended code and see how it works.
var myChartCircle = new Chart('chartProgress', {
type: 'doughnut',
data: {
datasets: [{
label: 'Africa / Population (millions)',
percent: 68,
backgroundColor: ['#5283ff']
}]
},
plugins: [{
beforeInit: (chart) => {
const dataset = chart.data.datasets[0];
chart.data.labels = [dataset.label];
dataset.data = [dataset.percent, 100 - dataset.percent];
}
},
{
beforeDraw: (chart) => {
var width = chart.chart.width,
height = chart.chart.height,
ctx = chart.chart.ctx;
ctx.restore();
var fontSize = (height / 150).toFixed(2);
ctx.font = fontSize + "em sans-serif";
ctx.fillStyle = "#9b9b9b";
ctx.textBaseline = "middle";
var text = chart.data.datasets[0].percent + "%",
textX = Math.round((width - ctx.measureText(text).width) / 2),
textY = height / 2;
ctx.fillText(text, textX, textY);
ctx.save();
}
}
],
options: {
maintainAspectRatio: false,
cutoutPercentage: 85,
rotation: Math.PI / 2,
legend: {
display: false,
},
tooltips: {
filter: tooltipItem => tooltipItem.index == 0
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="chartProgress"></canvas>

Related

How to draw the stroke behind bars in Chart.js?

I've wrote a custom Bar Chart in Chart.JS which on dataset hover highlight the bars by drawing a stroke on it the issue is that stroke is drawn over bars while i would make it something like 'background color' instead.
Like the bars are visible because the stroke color opacity is set to 0.05 while if i set it to 1 obviously those will not be visible anymore.
The code
class CustomBar extends Chart.BarController {
draw() {
super.draw(arguments);
if (this.chart.tooltip._active && this.chart.tooltip._active.length) {
const points = this.chart.tooltip._active[0];
const ctx = this.chart.ctx;
const x = points.element.x;
const topY = points.element.y + 150;
const width = points.element.width;
const bottomY = 0;
ctx.save();
ctx.beginPath();
ctx.moveTo(x, topY * 100);
ctx.lineTo(x + width * 1.3, bottomY);
ctx.lineWidth = width * 4.3;
ctx.strokeStyle = 'rgba(0, 0, 0, 0.05)';
ctx.stroke();
ctx.restore();
}
}
}
CustomBar.id = 'shadowBar';
CustomBar.defaults = Chart.BarController.defaults;
Chart.register(CustomBar);
You will need a custom plugin for this, in there you can specify that you want it to draw before the datasets are being drawn. You can do that like so:
Chart.register({
id: 'barShadow',
beforeDatasetsDraw: (chart, args, opts) => {
const {
ctx,
tooltip,
chartArea: {
bottom
}
} = chart;
if (!tooltip || !tooltip._active[0]) {
return
}
const point = tooltip._active[0];
const element = point.element;
const x = element.x;
const topY = -(element.height + 150);
const width = element.width;
const bottomY = 0;
const xOffset = opts.xOffset || 0;
const shadowColor = opts.color || 'rgba(0, 0, 0, 1)';
ctx.save();
ctx.beginPath();
ctx.fillStyle = shadowColor;
ctx.fillRect(x - (element.width / 2) + xOffset, bottom, width * 1.3 * 4.3, topY);
ctx.restore();
}
});
const options = {
type: 'bar',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: 'orange'
},
{
label: '# of Points',
data: [7, 11, 5, 8, 3, 7],
backgroundColor: 'pink'
}
]
},
options: {
plugins: {
barShadow: {
xOffset: -10,
color: 'red'
}
}
}
}
const ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.0/chart.js"></script>
</body>

How to add text inside the doughnut chart using Chart.js version 3.2.1

I am using in HTML using Canvas, how to use add the text inside Doughnut chart. Here is my javascript code and and HTML code. I have used chart js version 3.2.1 so please give solution for the same version(3).
var overallStatsCanvasCtx = document.getElementById('pademicOverallStats');
var dataPandemicEmp = {
labels: ['Normal', 'No Mask', 'Warning', 'High Temperature'],
datasets: [{
label: "Overall Statistics",
data: ['4000', '2000', '1500', '2500'],
backgroundColor: ['#43C187', '#8FC3F0', '#FFCD5E', '#FF4800'],
}]
};
var overallStatschartOptions = {
responsive: true,
plugins: {
legend: {
display: true,
align: 'center',
position: 'bottom',
labels: {
fontColor: '#474B4F',
usePointStyle: true,
}
}
},
};
var doughnutChart = new Chart(overallStatsCanvasCtx, {
type: 'doughnut',
data: dataPandemicEmp,
options: overallStatschartOptions,
});
<canvas id="pademicOverallStats"></canvas>
You will have to use a custom plugin for that
var data = {
labels: [
"Red",
"Blue",
"Yellow"
],
datasets: [{
data: [300, 50, 100],
backgroundColor: [
"#FF6384",
"#36A2EB",
"#FFCE56"
],
hoverBackgroundColor: [
"#FF6384",
"#36A2EB",
"#FFCE56"
]
}]
};
var promisedDeliveryChart = new Chart(document.getElementById('myChart'), {
type: 'doughnut',
data: data,
options: {
responsive: true,
plugins: {
legend: {
display: false
}
}
},
plugins: [{
id: 'text',
beforeDraw: function(chart, a, b) {
var width = chart.width,
height = chart.height,
ctx = 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();
}
}]
});
<body>
<canvas id="myChart"></canvas>
<script src="https://cdn.jsdelivr.net/npm/chart.js#3.2.0/dist/chart.min.js"></script>
</body>
var data = {
labels: [
"Red",
"Blue",
"Yellow"
],
datasets: [{
data: [300, 50, 100],
backgroundColor: [
"#FF6384",
"#36A2EB",
"#FFCE56"
],
hoverBackgroundColor: [
"#FF6384",
"#36A2EB",
"#FFCE56"
]
}]
};
var promisedDeliveryChart = new Chart(document.getElementById('myChart'), {
type: 'doughnut',
data: data,
options: {
responsive: true,
plugins: {
legend: {
display: false
}
}
},
plugins: [{
id: 'text',
beforeDraw: function(chart, a, b) {
var width = chart.width,
height = chart.height,
ctx = chart.ctx;
ctx.restore();
var fontSize = (height / 240).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();
}
}]
});
<body>
<canvas id="myChart"></canvas>
<script src="https://cdn.jsdelivr.net/npm/chart.js#3.2.0/dist/chart.min.js"></script>
</body>
I'm doing an inline plugin and using chartjs version 3.9.1. I have adjusted the other answers to fit my needs which take into account a chart title and legend. The text in the center of the circle is also based on the total of the 0th dataset.
plugins: [{
id: 'doughnutInteriorText',
beforeDraw: function(chart) {
var width = chart.chartArea.width,
height = chart.chartArea.height,
ctx = chart.ctx;
ctx.restore();
var fontSize = (height / 114).toFixed(2);
ctx.font = fontSize + "em sans-serif";
ctx.textBaseline = "middle";
var text = chart.data.datasets[0].data.reduce((partialSum, a) => partialSum + a, 0),
textX = Math.round((width - ctx.measureText(text).width) / 2),
textY = (height / 2) + chart.legend.height + chart.titleBlock.height;
ctx.fillText(text, textX, textY);
ctx.save();
}
}]

ChartJS - Show values in the center of each bar

See image below, I'm trying to set the value of each bar in the center of my stacked bar; so far I only got on the top and sometimes the position is off (see the 4% yellow in the third bar)
This is the code:
context.data.datasets.forEach(function (dataset) {
for (var i = 0; i < dataset.data.length; i++) {
var model = dataset._meta[Object.keys(dataset._meta)[0]].data[i]._model,
scale_max = dataset._meta[Object.keys(dataset._meta)[0]].data[i]._yScale.maxHeight;
var textY = model.y + 50;
if ((scale_max - model.y) / scale_max >= 0.5)
textY = model.y + 20;
fadeIn(ctx, dataset.data[i], model.x, textY, model.y > topThreshold, step);
}
});
var fadeIn = function(ctx, obj, x, y, black, step) {
var ctx = modifyCtx(ctx);
var alpha = 0;
ctx.fillStyle = black ? 'rgba(' + outsideFontColor + ',' + step + ')' : 'rgba(' + insideFontColor + ',' + step + ')';
ctx.fillText(obj.toString() + "%", x, y);
};
This can be done with the Plugin Core API. The API offers different hooks that may be used for executing custom code (that's probably what you already do). In your case, you can use the afterDraw hook as follows to draw text at the desired positions.
afterDraw: chart => {
let ctx = chart.chart.ctx;
ctx.save();
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.font = "12px Arial";
let xAxis = chart.scales['x-axis-0'];
let yAxis = chart.scales['y-axis-0'];
let datasets = chart.chart.data.datasets.filter(ds => !ds._meta[0].hidden);
xAxis.ticks.forEach((value, xIndex) => {
let x = xAxis.getPixelForTick(xIndex);
datasets.forEach((dataset, iDataset) => {
if (dataset.data[xIndex] > 3) {
let yValue = datasets.slice(0, iDataset)
.map(ds => ds.data[xIndex])
.reduce((a, b) => a + b, 0) +
dataset.data[xIndex] / 2;
let y = yAxis.getPixelForValue(yValue);
ctx.fillStyle = dataset.textColor;
ctx.fillText(dataset.data[xIndex] + '%', x, y);
}
});
});
ctx.restore();
}
Please take a look at below runnable code and see how it works.
const chart = new Chart('myChart', {
type: 'bar',
plugins: [{
afterDraw: chart => {
let ctx = chart.chart.ctx;
ctx.save();
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.font = "12px Arial";
let xAxis = chart.scales['x-axis-0'];
let yAxis = chart.scales['y-axis-0'];
let datasets = chart.chart.data.datasets.filter(ds => !ds._meta[0].hidden);
xAxis.ticks.forEach((value, xIndex) => {
let x = xAxis.getPixelForTick(xIndex);
datasets.forEach((dataset, iDataset) => {
if (dataset.data[xIndex] > 3) {
let yValue = datasets.slice(0, iDataset)
.map(ds => ds.data[xIndex])
.reduce((a, b) => a + b, 0) +
dataset.data[xIndex] / 2;
let y = yAxis.getPixelForValue(yValue);
ctx.fillStyle = dataset.textColor;
ctx.fillText(dataset.data[xIndex] + '%', x, y);
}
});
});
ctx.restore();
}
}],
data: {
labels: ['A', 'B', 'C', 'D', 'E'],
datasets: [{
label: 'Dataset 1',
data: [2.5, 48, 9, 17, 23],
backgroundColor: 'red',
textColor: 'white'
}, {
label: 'Dataset 2',
data: [2.5, 4, 4, 11, 11],
backgroundColor: 'orange',
textColor: 'black'
}, {
label: 'Dataset 3',
data: [95, 48, 87, 72, 66],
backgroundColor: 'green',
textColor: 'white'
}]
},
options: {
scales: {
xAxes: [{
stacked: true
}],
yAxes: [{
stacked: true,
ticks: {
beginAtZero: true
}
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script>
<canvas id="myChart" height="160"></canvas>

how can i use inline plugin inner title for chart js?

i am creating a JavaScript web page with two doughnut charts. to create the charts i'm using one function and calling it twice with different data for each chart. however when i do that the text in the middle of the doughnut chart is being changed for both charts not only for current one. how can i write the text individually for each?
this is my code
function chart(dummynames, dummyValues, dummyColors, percentage, id) {
//dummy names, dummy values and dummy colors are arrays
new Chart(document.getElementById(id), {
type: 'doughnut',
data: {
labels: dummynames,
datasets: [{
label: "tessers",
backgroundColor: dummyColors,
data: dummyValues,
}]
},
options: {
title: {
display: true,
align: 'center',
horizontalAlign: "center",
verticalAlign: "bottom",
dockInsidePlotArea: true
},
legend: {
display: false
},
cutoutPercentage: 70,
},
});
Chart.pluginService.register({
beforeDraw: function(chart) {
var width = chart.chart.width,
height = chart.chart.height + 35,
ctx = chart.chart.ctx;
ctx.restore();
var fontSize = (height / 200).toFixed(2);
ctx.font = fontSize + "em sans-serif";
ctx.textBaseline = "middle";
var text = percentage,
textX = Math.round((width - ctx.measureText(text).width) / 2),
textY = height / 2;
ctx.fillText(text, textX, textY);
ctx.save();
}
})
}
enter image description here
You should place Chart.pluginService.register outside of the chart function, thus making sure that it is invoked once only.
Please take a look at your amended code and see how it works.
Chart.pluginService.register({
beforeDraw: function(chart) {
var width = chart.chart.width,
height = chart.chart.height + 35,
ctx = chart.chart.ctx;
ctx.save();
var fontSize = (height / 200).toFixed(2);
ctx.font = fontSize + "em sans-serif";
ctx.textBaseline = "middle";
var text = chart.data.datasets[0].percentage,
textX = Math.round((width - ctx.measureText(text).width) / 2),
textY = height / 2;
ctx.fillText(text, textX, textY);
ctx.restore();
}
});
function chart(dummynames, dummyValues, dummyColors, percentage, id) {
new Chart(document.getElementById(id), {
type: 'doughnut',
data: {
labels: dummynames,
datasets: [{
label: "tessers",
backgroundColor: dummyColors,
data: dummyValues,
percentage: percentage
}]
},
options: {
title: {
display: true,
align: 'center',
horizontalAlign: "center",
verticalAlign: "bottom",
dockInsidePlotArea: true
},
legend: {
display: false
},
cutoutPercentage: 70,
},
});
}
chart(['A', 'B'], [5, 6], ['red', 'blue'], '26.846%', 'myChart1');
chart(['X', 'Y'], [7, 5], ['green', 'purple'], '19.451%', 'myChart2');
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script>
<div style="display: flex">
<div>
<canvas id="myChart1"></canvas>
</div>
<div>
<canvas id="myChart2"></canvas>
</div>
</div>

Chart.JS Error: this.scale is undefined

I'm trying since to days and really new to Chart.js. Everything seems to be clear but now i would like to put a label on top of every single bar.
Trying this i get an error: this.scale is undefined. I got the animation.onComplete Snippet out of the net but it seems i make a mistake. The Chart works fine .. i just don't get the labels on top of the bars. Maybe someone can please help me with this ?!
I also have a line chart with the same problem.
var ctx = document.getElementById("chartA").getContext("2d");
Chart.defaults.global.animation.duration = 2400;
Chart.defaults.global.animation.easing = "easeInOutQuad";
Chart.defaults.global.elements.point.radius = 4;
Chart.defaults.global.elements.point.hoverRadius = 5;
Chart.defaults.global.elements.point.hitRadius = 1;
var chart = new Chart(ctx, {
type: "bar",
data: {
labels: ["A","B","C"],
datasets: [{
label: "Test",
backgroundColor: "rgba(255, 99, 132, 0.2)",
borderColor: "#CF2748",
borderWidth: 1,
data: [10,20,30]
}]
},
options: {
tooltips: { mode: 'nearest', intersect: false },
layout: { padding: { left: 20, right: 0, top: 0, bottom: 0 } },
legend: { display: true, position: 'top' },
scales: {
yAxes: [{
ticks: { maxTicksLimit: 9, stepSize: 300, callback: function(value, index, values) { return value+" €"; } }
}]
},
animation: {
onComplete: function () {
var ctx = this.chart.ctx; // this part doesn't work
ctx.font = this.scale.font;
ctx.fillStyle = this.scale.textColor;
ctx.textAlign = "center";
ctx.textBaseline = "bottom";
this.datasets.forEach(function (dataset) {
dataset.bars.forEach(function (bar) {
ctx.fillText(bar.value, bar.x, bar.y - 5);
});
});
}
}
}
});
Thank you so much
Oliver
Thanks #Jeff I was testing around and get closer.
chart.data.datasets.forEach(function (dataset) {
dataset.data.forEach(function (value) {
ctx.fillText(value, x, y);
});
});
Now i have in "value" the right value. But i need to refer X and Y. Where do i get them? If i change X and Y with static value it works but all values were logically printed on the same space.
There are several issues with your code.
You could rather use the following chart plugin to accomplish the same :
Chart.plugins.register({
afterDatasetsDraw: function(chart) {
var ctx = chart.ctx;
chart.data.datasets.forEach(function(dataset, datasetIndex) {
var datasetMeta = chart.getDatasetMeta(datasetIndex);
datasetMeta.data.forEach(function(meta) {
var posX = meta._model.x;
var posY = meta._model.y;
var value = chart.data.datasets[meta._datasetIndex].data[meta._index];
// draw values
ctx.save();
ctx.textBaseline = 'bottom';
ctx.textAlign = 'center';
ctx.font = '16px Arial';
ctx.fillStyle = 'black';
ctx.fillText(value, posX, posY);
ctx.restore();
});
});
}
});
add this plugin at the beginning of your script.
ᴡᴏʀᴋɪɴɢ ᴇxᴀᴍᴘʟᴇ ⧩
Chart.plugins.register({
afterDatasetsDraw: function(chart) {
var ctx = chart.ctx;
chart.data.datasets.forEach(function(dataset, datasetIndex) {
var datasetMeta = chart.getDatasetMeta(datasetIndex);
datasetMeta.data.forEach(function(meta) {
var posX = meta._model.x;
var posY = meta._model.y;
var value = chart.data.datasets[meta._datasetIndex].data[meta._index];
// draw values
ctx.save();
ctx.textBaseline = 'bottom';
ctx.textAlign = 'center';
ctx.font = '16px Arial';
ctx.fillStyle = 'black';
ctx.fillText(value, posX, posY);
ctx.restore();
});
});
}
});
var ctx = document.getElementById("chartA").getContext("2d");
Chart.defaults.global.animation.duration = 2400;
Chart.defaults.global.animation.easing = "easeInOutQuad";
Chart.defaults.global.elements.point.radius = 4;
Chart.defaults.global.elements.point.hoverRadius = 5;
Chart.defaults.global.elements.point.hitRadius = 1;
var chart = new Chart(ctx, {
type: "bar",
data: {
labels: ["A", "B", "C"],
datasets: [{
label: "Test",
backgroundColor: "rgba(255, 99, 132, 0.2)",
borderColor: "#CF2748",
borderWidth: 1,
data: [10, 20, 30]
}]
},
options: {
tooltips: {
mode: 'nearest',
intersect: false
},
layout: {
padding: {
left: 20,
right: 0,
top: 0,
bottom: 0
}
},
legend: {
display: true,
position: 'top'
},
scales: {
yAxes: [{
ticks: {
maxTicksLimit: 9,
stepSize: 300,
callback: function(value, index, values) {
return value + " €";
}
}
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="chartA"></canvas>

Categories