简体   繁体   中英

chart.js plotting timeseries

Attempting to pass through data from django to a webpage to render a responsive chart. The data are being passed correctly to js, but I am driving myself crazy trying to understand why charts.js is throwing an error.

I have hardcoded some data for example:

function setLineChart() {
    var ctx = document.getElementById("myLineChart").getContext('2d');
    var dat_1 = {
        label: 'things',
        borderColor: 'blue',
        data: [
            {t: new Date("04/01/2020"), y: 310},
            {t: new Date("04/02/2020"), y: 315},
            {t: new Date("04/03/2020"), y: 320},
            ]
    };
    var myLineChart = new Chart(ctx, {
        type: 'line',
        data: {
            datasets: [dat_1]
        },
        options: {
            scales: {
                xAxes: [{
                    type: 'time',
                    time: {
                        unit: 'day'
                    },
                }],
                yAxes: [{
                    ticks: {
                        beginAtZero: true
                    }
            }]
            }
        }
    })
}
<canvas id="myLineChart" width="600" height="600"></canvas>

And this returns a Uncaught TypeError: Cannot read property 'skip' of undefined error that I can't debug. setLineChart() gets called as part of an ajax response on a form update. When I comment out the options section, it does render a chart, but misses off the last data point, and has undefined as the x-axis marker.

Any help would be appreciated.

Chart.js internally uses Moment.js for the functionality of the time axis . Therefore you should use the bundled version of Chart.js that includes Moment.js in a single file.

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script>

This will solve your problem as the following amended code snippet illustrates.

 var ctx = document.getElementById("myLineChart").getContext('2d'); var dat_1 = { label: 'things', borderColor: 'blue', data: [ { t: new Date("04/01/2020"), y: 310 }, { t: new Date("04/02/2020"), y: 315 }, { t: new Date("04/03/2020"), y: 320 }, ] }; var myLineChart = new Chart(ctx, { type: 'line', data: { datasets: [dat_1] }, options: { scales: { xAxes: [{ type: 'time', time: { unit: 'day' }, }], yAxes: [{ ticks: { beginAtZero: true } }] } } });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script> <canvas id="myLineChart" height="90"></canvas>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM