3

I am trying to make a chart in Chart.js which outputs the world's population (this is just an example which I am gonna be using for a different project), my problem is that one of the countries doesn't have a population (Somethingistan), I do want the country to be listed in the position is it right now but I want to population to 'skip' it, is there any way of doing this?

This is me making my chart

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,784,433]
            }
        ]
    },
    options: {
        legend: { display: false },
        title: {
            display: true,
            text: 'Predicted world population (millions) in 2050'
        }
    }
});

I have also already tried this method:

data: [{x:"Africe", y:2478},{x:"Asia", y:5267},{x:"Europa", y:734},{x:"North America", y:784}]

But I don't think it will work, but basically that is what I want to achieve, to bind data to specific labels.

peaceduck
  • 231
  • 1
  • 2
  • 9

1 Answers1

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>
WhiteHat
  • 59,912
  • 7
  • 51
  • 133