sparkle
sparkle

Reputation: 7390

Chartjs time serie in wrong format

I am using Chartjs to display time series, but when I pass this data as input nothing it's displayed.

enter image description here

Data

let serie = [{"x": 1594887960*1000, "y": 95.95},{"x": 1596488640*1000,"y": 42.95}]
      

this.chartJS.data.datasets[0].data = serie
this.chartJS.update()

if instead I use this, it works.

serie = [{"x": '2020-01-01', "y": 95.95},{"x": '2020-01-31',"y": 42.95}]

enter image description here

but I'd like to timestamp for performance, easy sorting, and better labels ( DAY MONTH format).

Chart JS options

this.chartJS = new Chart(this.$refs.chart, {
    type: 'line',
    data: {
        datasets: [
            {
                data: [],
                fill: false,
                borderColor: 'rgb(75, 192, 192)',
                stepped: false,
            }
        ]
    },
    options: {
        title:      {
            display: true,
            text:    "Chart.js Time Scale"
        },
        scales: {
            xAxes: [{
                type:       "time",
                time:       {
                    tooltipFormat: 'll',
                    time: {
                        unit: 'day'
                    }
                },
                scaleLabel: {
                    display:     true,
                    labelString: 'Date'
                }
            }]
        }
    }
})

EDIT:

Solved using

import Chart from 'chart.js/auto';
import { format } from 'date-fns'

format(new Date(data[0]*1000), 'yyyy-MM-dd')

Upvotes: 0

Views: 557

Answers (1)

uminder
uminder

Reputation: 26150

Your code works just fine with the initial data you provided. I only corrected the xAxes.time definition but even without this change, it works.

Maybe you're using an outdated version of Chart.js v2 or you don't use the bundled version of Chart.js that includes Moment.js (required for the time axis) in a single file.

Please take a look at your runnable code below:

const chartJS = new Chart('canvas', {
  type: 'line',
  data: {
    datasets: [{
      data: [],
      fill: false,
      borderColor: 'rgb(75, 192, 192)',
      stepped: false,
    }]
  },
  options: {
    title: {
      display: true,
      text: "Chart.js Time Scale"
    },
    scales: {
      xAxes: [{
        type: "time",
        time: {
          unit: 'day',
          tooltipFormat: 'll'
        },
        scaleLabel: {
          display: true,
          labelString: 'Date'
        }
      }]
    }
  }
});

let serie = [{"x": 1594887960*1000, "y": 95.95},{"x": 1596488640*1000,"y": 42.95}];      
chartJS.data.datasets[0].data = serie;
chartJS.update();
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.bundle.min.js"></script>
<canvas id="canvas"></canvas>

Upvotes: 1

Related Questions