Chartjs-ChartJS Bar chart with time scale โ€“ Bars overlap with each other

0๐Ÿ‘

โœ…

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>

Leave a comment