I'm trying to get the percentages for each category of the products.
If i copy this jsfiddle example in my extisting Laravel project i'm supposed to get a pie chart from Chart.js with percentages. I do get the chart but the percentages don't show. Am i doing something wrong?
I have marked the section from the example in comments.
Link to the Jsfiddle: https://jsfiddle.net/a1Lvn4eb/55/
My Code:
@extends('admin::_layouts.base')
@section('content')
<html>
<head>
<title>Title</title>
<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-xl-6">
<div class="card">
<div class="card-body">
<div class="card-title font-size-lg">Revenue by category</div>
<canvas id="Categories"></canvas>
</div>
</div>
</div>
</div>
@foreach($reports as $report)
{!! $report->toHtml() !!}
@endforeach
</div>
</body>
</html>
<script>
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, categories) => {
let sum = 0;
let dataArr = categories.chart.data.datasets[0].data;
dataArr.map(data => {
sum += data;
});
let percentage = (value*100 / sum).toFixed(2)+"%";
return percentage;
},
color: '#fff',
}
}
};
var categories = document.getElementById('Categories').getContext('2d');
var myChart = new Chart(categories, {
type: 'pie',
data: {
datasets: data
},
options: options
});
</script>
@endsection
Sorry if my code is messy! I'm a beginner in programming.