[Chartjs]-How do I get a chart.js chart to display data in a Node/React web application?

1👍

Thanks to cdm for putting me in the right direction. I remembered that one of my github repositories has chart.js implementations that my teammates made which replaced the google charts that I was using originally.

They are implemented like so:

makeChart(datapoints) {
    this.setState({ data: datapoints })
    var ctx = document.getElementById("myChart");
    var datapoints = datapoints.slice(0,100)
    var config = {
        type: 'line',
        data: {
            labels: this.linspace(0,datapoints[0],datapoints.length),
            datasets: [{
                data: datapoints,
                label: "Price:",
                borderColor: "#3e95cd",
                fill: false
            }]
        },
        options: {
            title: {
                display: true,
                text: 'WTI Closing Price'
            },
            legend: {
                display: false
            }
        }
    }
    var myChart = new Chart(ctx, config );
}

This configuration format works as expected producing the chart below:
enter image description here

For completeness, for those who may use this exact code, the linspace function is implemented as follows:

precisionRound(number, precision) {
    var factor = Math.pow(10, precision);
    return Math.round(number * factor) / factor;
}

linspace (a, b, n) {
    if (typeof n === 'undefined') n = Math.max(Math.round(b - a) + 1, 1)
    if (n < 2) {
        return n === 1 ? [a] : []
    }
    var i,ret = Array(n)
    n--
    for (i = n;i >= 0;i--) {
        ret[i] = this.precisionRound((i * b + (n - i) * a) / n, 2)
    }
    return ret
}

3👍

I could be wrong, but it looks like the input data for your linechart is in an incorrect format. Looking here at chartJs’ documentation, you either have to specify the x and y of each point individually using an array of objects, or in your case, when passing an array of numbers, specify a labels array.

When the data array is an array of numbers, the x axis is generally a category. The points are placed onto the axis using their position in the array. When a line chart is created with a category axis, the labels property of the data object must be specified.

You can see how to do that here, so your chart data param should look like this:

let chart = new Chart(ctx, {
    type: ...
    data: {
        labels: ['January', 'February', 'March', 'April', 'May', 'June'],
        datasets: ...
    },
});

Leave a comment