noblemfd
1 week ago

How to Display both count and percentage (%) in chart js pie chart

Posted 1 week ago by noblemfd

In my Laravel-5.8, I have used chartjs to display total male and female counts (total number of male and female)

as shown below:

Controller:

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);       
}

view

          <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>

Diagram:

https://i.stack.imgur.com/JxEuw.png

What I have as shown above only displays Total counts per Gender as shown above.

How do I make it also to include the percentage per Gender?

Thank you.

Please sign in or create an account to participate in this conversation.