score:63
Updated fiddle with 2 decimal precision.
You were not computing the sum, instead storing the current value in sum only for every value.
Here is the working fiddle : https://jsfiddle.net/a1Lvn4eb/55/
var data = [{
data: [50, 55, 60, 33],
labels: ["India", "China", "US", "Canada"],
backgroundColor: [
"#4b77a9",
"#5f255f",
"#d21243",
"#B27200"
],
borderColor: "#fff"
}];
var options = {
tooltips: {
enabled: false
},
plugins: {
datalabels: {
formatter: (value, ctx) => {
let sum = 0;
let dataArr = ctx.chart.data.datasets[0].data;
dataArr.map(data => {
sum += data;
});
let percentage = (value*100 / sum).toFixed(2)+"%";
return percentage;
},
color: '#fff',
}
}
};
var ctx = document.getElementById("pie-chart").getContext('2d');
var myChart = new Chart(ctx, {
type: 'pie',
data: {
datasets: data
},
options: options
});
score:0
if you use nodejs: follow the steps:
- npm install chartjs-plugin-datalabels
- import ChartDataLabels from 'chartjs-plugin-datalabels';
- Chart.register(...registerables, ChartDataLabels);
- copy the code from the over comments...
https://chartjs-plugin-datalabels.netlify.app/guide/#table-of-contents
score:0
As some people mentioned, context.dataset._meta[0].total
seem to have been removed in chart.js version 3 and above and didn't work anymore. Instead, I used context.chart.getDatasetMeta(0).total
and it worked for me - it shows percentage values in pie chart and value gets updated based on the filtered total when the legends are clicked.
options:{
plugins:{
datalabels: {
color: 'white',
formatter: function(value, context) {
return Math.round(value/context.chart.getDatasetMeta(0).total * 100) + "%" ;
}
}
}
}
score:1
I am using ChartJS v3.7.0 and chartjs-plugin-datalabels v2.0.0 and this answer:
https://stackoverflow.com/a/59403435/6830478
does not really work for me, while I just wanted to keep the percentages up to date, also when hiding elements. It seems that ctx.dataset._meta
is not available anymore. I came up with some ugly monkey patch:
formatter: function(value, context) {
var hiddens = context.chart._hiddenIndices;
var total = 0;
var datapoints = context.dataset.data;
datapoints.forEach((val, i) => {
if (hiddens[i] != undefined) {
if (!hiddens[i]) {
total += val;
}
} else {
total += val;
}
});
var percentage = (value / total * 100).toFixed(2) + '%';
var out = context.chart.data.labels[context.dataIndex] + '\n' + percentage;
return out;
}
Hopw this might help anybody. Cheers.
score:3
This is update for chart.js >= 3.x and chartjs-plugin-datalabels >= 2.x
chartjs-plugin-datalabels
plugin no longer registers itself automatically
(docs)
You have to do it manually
Register plugin for all charts
Chart.register(ChartDataLabels)
or only to specific charts
var chart = new Chart(ctx, {
plugins: [ChartDataLabels],
options: {
// ...
}
})
And here's the code below to render the pie chart
var data = [{
data: [50, 55, 60, 33],
backgroundColor: [
"#4b77a9",
"#5f255f",
"#d21243",
"#B27200"
],
borderColor: "#fff"
}];
var options = {
tooltips: {
enabled: false
},
plugins: {
datalabels: {
formatter: (value, ctx) => {
const datapoints = ctx.chart.data.datasets[0].data
const total = datapoints.reduce((total, datapoint) => total + datapoint, 0)
const percentage = value / total * 100
return percentage.toFixed(2) + "%";
},
color: '#fff',
}
}
};
var ctx = document.getElementById("pie-chart").getContext('2d');
var myChart = new Chart(ctx, {
type: 'pie',
data: {
labels: ['India', 'China', 'US', 'Canada'],
datasets: data
},
options: options,
plugins: [ChartDataLabels],
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.6.2/chart.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-datalabels/2.0.0/chartjs-plugin-datalabels.min.js"></script>
<style>
.container {
width: 40%;
margin: 5px auto;
}
</style>
<div class="container">
<canvas id="pie-chart"></canvas>
</div>
score:4
You could use the tooltip with an Array reducer to perform the percentage calculation and display it.
tooltips: {
callbacks: {
label: function (tooltipItem, data) {
try {
let label = ' ' + data.labels[tooltipItem.index] || '';
if (label) {
label += ': ';
}
const sum = data.datasets[0].data.reduce((accumulator, curValue) => {
return accumulator + curValue;
});
const value = data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
label += Number((value / sum) * 100).toFixed(2) + '%';
return label;
} catch (error) {
console.log(error);
}
}
}
}
score:6
The problem is how you're calculating sum. See below.
var data = [{
data: [50, 55, 60, 33],
labels: ["India", "China", "US", "Canada"],
backgroundColor: [
"#4b77a9",
"#5f255f",
"#d21243",
"#B27200"
],
borderColor: "#fff"
}];
var options = {
tooltips: {
enabled: false
},
plugins: {
datalabels: {
formatter: (value, ctx) => {
let datasets = ctx.chart.data.datasets;
if (datasets.indexOf(ctx.dataset) === datasets.length - 1) {
let sum = datasets[0].data.reduce((a, b) => a + b, 0);
let percentage = Math.round((value / sum) * 100) + '%';
return percentage;
} else {
return percentage;
}
},
color: '#fff',
}
}
};
var ctx = document.getElementById("pie-chart").getContext('2d');
var myChart = new Chart(ctx, {
type: 'pie',
data: {
datasets: data
},
options: options
});
score:10
I like to add a little in accepted answer,
ctx.chart.data.datasets[0].data
always gives you entire data even if you filter out some data by clicking on legend, means you will always get same percentage for a country even if you filter out some countries.
I have used context.dataset._meta[0].total
to get the filtered total.
Here is the working snippet:
var data = [{
data: [50, 55, 60, 33],
backgroundColor: [
"#4b77a9",
"#5f255f",
"#d21243",
"#B27200"
],
borderColor: "#fff"
}];
var options = {
tooltips: {
enabled: true
},
plugins: {
datalabels: {
formatter: (value, ctx) => {
let sum = ctx.dataset._meta[0].total;
let percentage = (value * 100 / sum).toFixed(2) + "%";
return percentage;
},
color: '#fff',
}
}
};
var ctx = document.getElementById("pie-chart").getContext('2d');
var myChart = new Chart(ctx, {
type: 'pie',
data: {
labels: ['India', 'China', 'US', 'Canada'],
datasets: data
},
options: options
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@0.7.0"></script>
<canvas id="pie-chart"></canvas>
Source: stackoverflow.com
Related Query
- ChartJS: datalabels: show percentage value in Pie piece
- chartjs plugin datalabels does not show value on charts
- Show bar with zero value in ChartJs v2
- chartjs datalabels change font and color of text displaying inside pie chart
- ChartJS Line Graph - Multiple Lines, Show one Value on Tooltip
- ChartJS – How to show border on empty pie chart?
- Datalabels plugin chartjs showing '[object]' instead of value
- How to show percentage (%) using chartjs-plugin-labels ( Pie chart ) in angular 2/8
- ChartJS show value in legend (Chart.js V3.5)
- ChartJS version 3 how to add percentage to pie chart tooltip
- how to add percentage value to legend field in pie chart using chart.js
- How to show slice value inside of slice in pie chart using chart.js
- How can I show chartjs datalabels only last bar?
- ChartJS Pie Chart How default just show 2 legend datas
- how to show bar value on the top of each bar in chartjs
- ChartJS - Show percentage base on data on hover (AngularJS)
- ChartJS - Show percentage on hover (AngularJS)
- Drawing pie segment percentage in middle of doughnut with chartjs issue
- Is there any way to show tooltip by default (without hover pie chart) on chartjs
- Laravel - How to Display both count and percentage (%) in chartjs pie chart
- I want to show the value of label inside the pie graph. (vue-chartjs / pieceLabel)
- Chartjs sample line chart setup doesn't show dataLabels
- I am Creating pie chart using Chartjs 2.6.0. I want to show label on Slices
- Chart.js Show labels on Pie chart
- Chartjs random colors for each part of pie chart with data dynamically from database
- ChartJS – is there any way to remove blank space around pie charts?
- Truncating canvas labels in ChartJS while keeping the full label value in the tooltips
- chart.js: Show labels outside pie chart
- show label in tooltip but not in x axis for chartjs line chart
- chartjs show dot point on hover over line chart
More Query from same tag
- How to move Chart.js legend?
- Ng2-Charts in Angular: Is 'Auto' supported for display property of Axes
- ChartJS pie chart, "filling" each segment to indicate another dimension
- Placing canvas (chart.js line chart) inside an SVG using d3.js
- Chart.js letter spacing very awkward
- Charts flickering
- ng2 charts on Angular 9 not responsive
- How to add Dyamic JSON Dropdown Menu in Angular JS
- chartjs - How to use differente color if value is lower than previous value?
- ChartJs - Labelling minimum and maximum value of the Y Axis
- Why is chart.js not showing charts?
- Define backgroundColor from data in chartJS
- How to hide tooltip for selected datasets? - Chart.js v2.8
- is it possible to sum up the properties of an array of objects and to filter it according to another property?
- Stacked Bar Chart, Two on Same Line w/ Same Color
- ng2-charts - bar chart, showing only one color
- How to get the database data into ChartJS using codeigniter
- Drawing line chart in chart.js with json response
- How to create a line on a chart using chartjs-plugin-annotation
- Converting ChartJSCore to Highcharts.net - issue with dynamic series data in a loop
- how to use chart.js in angular 7
- Chart.js data/label scale
- chartjs: trying to rotate the y-Axis label
- Chart.js2 Radar, how to configure the label padding/spacing?
- ChartJS have xAxes labels match data source
- How to make rectangle in chart.js
- How to create a rounded rectangle using ChartJS
- ChartJS click on bar and change it's background color
- Draw a single frame in Chart.js
- Chartjs Array.join