0
votes

I'm trying to create a ChartJs Bar chart which contains date on labels.

The chart bars over lap with each other unevenly. Works well when the time scale is removed however, the labels are not date sorted. The labels and data are dynamically populated, so cannot sort it before rendering.

Below is the sample image,

enter image description here

And, if the scales (xAxis) is removed, it give proper output (but not sorted)

enter image description here

example: https://codepen.io/karthikkbala/pen/QWjVQqb

Sample data:

[ "2020-05-13", "2020-05-11", "2020-05-12", "2020-05-14", "2020-05-09", "2020-05-10", ] 
[ 20, 11, 9, 22, 11, 9, ]
1

1 Answers

0
votes

You can omit labels in the chart configuration and instead generate data as individual points through objects containing x and y properties as shown here.

const labels = ["2020-05-13", "2020-05-11", "2020-05-12", "2020-05-14", "2020-05-09", "2020-05-10"];
const baseData = [20, 11, 9, 22, 11, 9];
const data = labels.map((l, i) => ({ x: l, y: baseData[i] }));

This produces the following data.

[
  { "x": "2020-05-13", "y": 20 },
  { "x": "2020-05-11", "y": 11 },
  { "x": "2020-05-12", "y": 9 },
  { "x": "2020-05-14", "y": 22 },
  { "x": "2020-05-09", "y": 11 },
  { "x": "2020-05-10", "y": 9 }
]

The xAxis would then have to be defined as follows:

xAxes: [{
  offset: true,
  type: 'time',
  time: {
    unit: 'day',   
    source: 'data',
    tooltipFormat: 'MMM DD' 
  }
}],

Please have a look at your amended code below.

const labels = ["2020-05-13", "2020-05-11", "2020-05-12", "2020-05-14", "2020-05-09", "2020-05-10"];
const baseData = [20, 11, 9, 22, 11, 9];
const data = labels.map((l, i) => ({ x: l, y: baseData[i] }));

var chartData = {
  datasets: [{
    label: "All Detections",
    backgroundColor: "#02a499",
    borderColor: "#ffffff",
    borderWidth: 1,
    hoverBackgroundColor: "#02a499",
    hoverBorderColor: "#02a499",
    data: data
  }]
};

new Chart("ChartByDate", {
  type: 'bar',
  data: chartData,
  options: {
    scales: {
      xAxes: [{
        offset: true,
        type: 'time',
        time: {
          unit: 'day',   
          source: 'data',
          tooltipFormat: 'MMM DD' 
        }
      }],
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script>
<canvas id="ChartByDate"></canvas>