Chartjs-Vue Chart.js — can I give a line chart a default value for missing data?

1👍

I’m assuming you have some kind of regular time interval for your labels.

In Chart.js datasets are mapped to labels by their indexes in the arrays. Chart.js doesn’t really know where the “gaps” in your data are. Also Chart.js doesn’t know the date interval used for your label. I assume this choice of design in Chart.js is for performance reasons.

This would work as expected:

data: [1,0,0,10]
labels: ['June','July','Aug', 'Sept']

Here Chart.js would assume the first two values are for June and July:

data: [1,10]
labels: ['June','July','Aug','Sept']

Here Chart.js has no idea that July and Aug are missing:

data: [1,10]
labels: ['June','Sept']

If you API returns data like this:

{'June': 1, 'July': 0, 'Aug': 0, 'Sept': 10}

Then you can just do this:

const labels = Object.keys(response);
const datasets = [];
datasets.push({
  label: 'Line 1',
  data: labels.map(date => response[date]),
});
this.renderChart({
  labels,
  datasets,
});

You can use something like this in your backend to fill out the empty dates/months etc.

$interval = \DateInterval::createFromDateString('1 month');
$datePeriod = new \DatePeriod($begin, $interval, $end);
foreach ($datePeriod as $dt) {
  if (!isset($data[$dt->format('Y.m')])) {
    $data[$dt->format('Y.m')] = 0;
  }
}

Hope this helps.

Leave a comment