在我的Laravel-5.8中,我使用chartjs来显示男性和女性的总数(男性和女性的总数)
如下所示:
控制器:
public function report()
{
$userCompany = Auth::user()->company_id;
$userId = Auth::user()->id;
$gender_record = HrEmployee::selectRaw('count(gender_id) as count,gender_id, if (gender_id = 1, "Male", "Female") as gender')->where('company_id', $userCompany)->groupBy('gender_id')->get();
$gender_data = [];
foreach($gender_record as $row) {
$gender_data['gender_label'][] = $row->gender;
$gender_data['gender_data'][] = (int) $row->count;
}
$gender_data['gender_chart_data'] = json_encode($gender_data);
return view('report-default', $gender_data);
}
视图
<div class="card-body">
<canvas id="empGender" style="min-height: 250px; height: 250px; max-height: 250px; max-width: 100%;"></canvas>
</div>
<script src="{{ asset('theme/adminlte3/plugins/chart.js/Chart.min.js') }}"></script>
<script>
$(function () {
/* ChartJS
* -------
* Charts using ChartJS
*/
//-------------
//- GENDER-EMPLOYEE CHART -
//-------------
// Get context with jQuery - using jQuery's .get() method.
var genderData = JSON.parse(`<?php echo $gender_chart_data; ?>`);
var genderChartCanvas = $('#empGender').get(0).getContext('2d')
var genderData = {
labels: genderData.gender_label,
datasets: [
{
data: genderData.gender_data,
backgroundColor : [
'#f56954',
'#00a65a',
'#f39c12',
'#00c0ef',
],
borderColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
],
borderWidth: 1
}
]
}
var genderOptions = {
maintainAspectRatio : true,
responsive : true,
cutoutPercentage: 80,
}
//Create pie or douhnut chart
var genderChart = new Chart(genderChartCanvas, {
type: 'doughnut',
data: genderData,
options: genderOptions
})
})
</script>
上面显示的我仅显示如上所述的每个性别的总数。
我如何也要包括每性别的百分比?
谢谢。
您可以通过如下定义tooltip label callback函数来执行此操作。
tooltips: {
callbacks: {
label: (tooltipItem, data) => {
var value = data.datasets[0].data[tooltipItem.index];
var total = data.datasets[0].data.reduce((a, b) => a + b, 0);
var pct = 100 / total * value;
var pctRounded = Math.round(pct * 10) / 10;
return value + ' (' + pctRounded + '%)';
}
}
}
请查看下面的可运行代码段。
new Chart('empGender', {
type: 'doughnut',
data: {
labels: ['Male', 'Female'],
datasets: [{
backgroundColor: ['#f56954', '#00a65a'],
borderColor: ['rgba(255, 99, 132, 1)', 'rgba(54, 162, 235, 1)'],
data: [17, 7],
borderWidth: 1
}]
},
options: {
maintainAspectRatio: true,
responsive: true,
cutoutPercentage: 80,
tooltips: {
callbacks: {
label: (tooltipItem, data) => {
var value = data.datasets[0].data[tooltipItem.index];
var total = data.datasets[0].data.reduce((a, b) => a + b, 0);
var pct = 100 / total * value;
var pctRounded = Math.round(pct * 10) / 10;
return value + ' (' + pctRounded + '%)';
}
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="empGender" height="100"></canvas>