Autofill 0 value to undefined xAxes

Viewed 34

I got a series of data which represents how many downloads are in a day, but on chart.js if I skipped a day, the yAxes is not auto-filling the skipped day to 0 but instead, it skipped the xAxes without any data being represented.

So here's an example of the array labels: [ 'Wed Jun 26 2019', 'Tue Jun 25 2019', 'Mon Jun 24 2019', 'Sun Jun 23 2019', // Skipped a day here 'Fri Jun 21 2019', 'Wed Jun 12 2019', 'Mon Jun 10 2019', 'Fri Jun 07 2019' ] values: [5, 2, 1, 4, 3, 5, 1, 4]

this.chart = new Chart(this.$refs.chart, {
        type: 'line',
        data: {
          labels: labels,
          datasets: [
            {
              data: values
            }
          ]
        },
        options: {
          scales: {
            xAxes: [
              {
                type: 'time',
                distribution: 'linear',
                time: {
                  displayFormats: {
                    hour: 'MMM DD'
                  },
                  min: new Date().getTime() - 86400000 * 7, // Displaying data from last 7 days
                  max: new Date().getTime()
                },
                ticks: {
                  maxTicksLimit: 6,
                  fontFamily: 'Quicksand'
                }
              }
            ],
            yAxes: [
              {
                ticks: {
                  maxTicksLimit: 4,
                  fontFamily: 'Quicksand'
                }
              }
            ]
          }
        }
      })

here's my chart.js output:

as you can see there, Jun 22 and Jun 27 is skipped instead of autofill it to 0.

as you can see there, Jun 22 and Jun 27 is skipped instead of autofill it to 0.

1 Answers

I created this plugin based on this thread right here, and it's working beautifully

beforeInit(labels, values) {
  let min, max, newLabels = [], newData = [], assoc = {}
  /* 
  Loop through the dates (config labels).
  Find the min and max date, and add all dates/values to assoc.
  */
  let dates = labels
  for(let i = 0; i < dates.length; i++){
    /* Current date */
    let val = moment(dates[i])
    /* If current date the min, set as min */
    if(!min || min.diff(val) > 0)
      min = val
    /* Store all in assoc array */
    assoc[val.format('DD MMM')] = values[i]
  }
  max = moment(new Date().getTime())
  /* From the min date, and looping by minUnit until max date */
  for(let d = min; max.diff(d) > 0; d.add(1, 'day')) { 
    /* Current date */
    let cur = d.format('DD MMM')
    newLabels.push(cur)
    /* Add zero for day if not represented */
    if (!assoc[cur]) {
      newData.push(0)
    } else {
      newData.push(assoc[cur])
    }
  }
  return { newData, newLabels }
}

Proof

Related