自动将0值填充为未定义的xAxes

时间:2019-06-26 23:34:25

标签: javascript charts

我得到了一系列数据,这些数据代表一天的下载量, 但是在chart.js上,如果我跳过了一天,则yAxes不会将跳过的日期自动填充为0,而是会跳过xAxes,而不会显示任何数据。

所以这是数组的一个例子 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'
                }
              }
            ]
          }
        }
      })

这是我的chart.js输出:

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

如您所见,将跳过6月22日和6月27日,而不是将其自动填充为0。

1 个答案:

答案 0 :(得分:0)

我是根据here这个线程创建此插件的,它的运行很漂亮

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