[Chartjs]-Chart.js – bind data in dataset to specific chart labels

0👍

when drawing the chart, you need two arrays –> labels & data

each array should have the same number of elements,
the first element in the data array, will be “bound” to the first label in the labels array

if a label doesn’t have a value, just use null

labels: ['Africa', 'Asia', 'Europe', 'Somethingistan', 'North America']

data: [2478,5267,734,null,784]

in the above snippet,

2478 will be bound to 'Africa'
null will be bound to 'Somethingistan'

see following working snippet…

window.onload = function () {
  new Chart(document.getElementById('bar-chart'), {
    type: 'bar',
    data: {
      labels: ['Africa', 'Asia', 'Europe', 'Somethingistan', 'North America'],
      datasets: [{
        label: 'Population (millions)',
        backgroundColor: ['#3e95cd', '#8e5ea2','#3cba9f','#e8c3b9','#c45850'],
        data: [2478,5267,734,null,784]
      }]
    },
    options: {
      legend: {
        display: false
      },
      title: {
        display: true,
        text: 'Predicted world population (millions) in 2050'
      }
    }
  });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.4.0/Chart.min.js"></script>
<div class="container">
  <canvas id="bar-chart"></canvas>
<div>

Leave a comment