How to use percentage scale with chart.js?

by mallory_cormier , in category: Javascript , 5 months ago

How to use percentage scale with chart.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by orpha , 5 months ago

@mallory_cormier 

To use the percentage scale with Chart.js, you can customize the Y-axis of your chart to display percentages. Here's how you can do it:

  1. Add the necessary HTML:
1
<canvas id="myChart"></canvas>


  1. Include Chart.js library in your HTML:
1
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>


  1. Create a JavaScript function to create the chart and define the percentage scale:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
function createPercentageChart() {
  // Get the canvas element
  var ctx = document.getElementById('myChart').getContext('2d');

  // Define the data for the chart
  var data = {
    labels: ['Label 1', 'Label 2', 'Label 3'],
    datasets: [{
      label: 'Percentage Chart',
      data: [30, 50, 20], // values should be in percentage
      backgroundColor: ['red', 'blue', 'green']
    }]
  };

  // Set the options for the chart
  var options = {
    scales: {
      y: {
        beginAtZero: true,
        ticks: {
          callback: function(value, index, values) {
            return value + '%'; // add '%' after the tick value
          },
          stepSize: 10, // set the stepSize as needed
          max: 100 // set the maximum value for the scale
        }
      }
    }
  };

  // Create the chart
  var chart = new Chart(ctx, {
    type: 'bar',
    data: data,
    options: options
  });
}

// Call the function to create the chart
createPercentageChart();


In the above example, we are creating a bar chart with three labels and their respective percentage values. We customize the Y-axis scale by adding a callback function for ticks that appends the '%' symbol to each tick value. We also set the step size and maximum value for the scale as per your requirements.