Search code examples
javascriptvue.jschart.jsvue-chartjs

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


I'm creating a line chart with Vue.js, but there are gaps in the data I'm passing to renderChart(). I haven't been able to find anything so far in the documentation but I'm still curious -- is there a way to fill in those gaps with a default value? I'd use zero in this case but it would be cool if it was configurable. Or is my best bet to backfill the data with dummy values before passing it in to renderChart()?


Solution

  • 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.