[Chartjs]-Chart.js – Bar chart with linear cartesian (numerical) X axis?

1👍

You can specify the data of your dataset as objects with x/y coordinates but only when using the time scale. Therefore your data would have to be defined as follows.

data: [
  { x: '1', y: 1 },
  { x: '2', y: 2 },
  { x: '3', y: 3 },
  { x: '5', y: 1 },
  { x: '6', y: 5 },
  { x: '7', y: 1 },
],

Together with this, you’ll need to define the xAxis as follows:

xAxes: [{
  offset: true,
  type: 'time',
  time: {
    parser: 's',
    unit: 'second',
    displayFormats: {
      second: 's'
    }
  },
  ticks: {
    stepSize: 1
  },
  gridLines: {
    offsetGridLines: true
  },
}]

Please note that Chart.js uses Moment.js for the functionality of the time axis. Therefore you should use the bundled version of Chart.js that includes Moment.js in a single file.

Please have a look at the runnable code snippet below.

new Chart(document.getElementById("chart"), {
  type: "bar",
  data: {
    datasets: [{
      label: "My Dataset",
      data: [
        { x: '1', y: 1 },
        { x: '2', y: 2 },
        { x: '3', y: 3 },
        { x: '5', y: 1 },
        { x: '6', y: 5 },
        { x: '7', y: 1 },
      ],
      backgroundColor: ["rgba(255, 99, 132, 0.2)", "rgba(255, 159, 64, 0.2)", "rgba(255, 205, 86, 0.2)", "rgba(75, 192, 192, 0.2)", "rgba(54, 162, 235, 0.2)", "rgba(153, 102, 255, 0.2)"],
      borderColor: ["rgb(255, 99, 132)", "rgb(255, 159, 64)", "rgb(255, 205, 86)", "rgb(75, 192, 192)", "rgb(54, 162, 235)", "rgb(153, 102, 255)"],
      borderWidth: 1
    }]
  },
  options: {
    scales: {
      yAxes: [{      
        ticks: {
          beginAtZero: true,
          stepSize: 1
        }
      }],
      xAxes: [{
        offset: true,
        type: 'time',
        time: {
          parser: 's',
          unit: 'second',
          displayFormats: {
            second: 's'
          }
        },
        ticks: {   
          stepSize: 1
        },
        gridLines: {
          offsetGridLines: true
        },
      }]
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script>
<canvas id="chart" height="80"></canvas>

1👍

uminder’s answer is right, but the problem of using "seconds" as the time unit is that you cannot set values greater than 59 on the X axis. If you do, the chart will appear blank.

By just changing the time data to use years you will be able to set any value you want.

time: {
      parser: 'Y',
      unit: 'year',
      displayFormats: {
        year: 'Y'
      }
}

Leave a comment