简体   繁体   中英

Using unknown number of datasets in Chart.js

I'm still fairly new to javascript and this has got me banging my head against the wall. I'm sure it's really simple but for some reason I cannot seem to get this working correctly. I have seen similar questions on stackoverflow but I can't make them work for me.

I am trying to plot an unknown number of datasets onto a Chartjs graph. I am able to get the data (using PHP it is output as data attributes on child elements of the canvas) and store them to a variable $rows.

var $rows = $('#graphCanvas').find('> div')

I then iterate through the rows and calculate the dataset.

var colors = [ '#2685CB', '#4AD95A', '#FEC81B', '#FD8D14', '#CE00E6', '#4B4AD3', '#FC3026', '#B8CCE3', '#6ADC88', '#FEE45F'  ];

for (var i=0; i<$rows.length; i++) {
    datasetdata[i] = {
        label:"Test " + i,
        data: getdata($rows[i]),
        backgroundColor: colors[i],
        hoverBackgroundColor: colors[i],
        borderStyle: 'solid',
        borderWidth: 2,
    }
}

function getdata($rows) {
    //returns raw data
}

This all works well however the problem starts when I try to use datasetdata

var graphContext = document.getElementById("graphCanvas").getContext("2d");
var graphData = {
    labels: labels,
    datasets: [datasetdata]
};

If I use it with an index it works fine: datasetdata[0]

If I knew for sure how many datasets there would be I could just add their indexes and it would be fine.

Any insight into what I'm doing wrong would be great

Problem:

You have an extra set of brackets surrounding the datasetdata variable.

Solution:

Remove the brackets and set the datasets to just datasetdata :

var graphData = {
    labels: labels,
    datasets: datasetdata
};

Explanation:

The datasets option accepts a parameter that is an array of dataset objects. The wanted structure looks as following:

datasets: [
    { dataset1 },
    { dataset2 }
]

In your code, you surrounded the datasetdata by a set of brackets:

var graphData = {
    labels: labels,
    datasets: [datasetdata]
};

By adding another set of brackets, you are basically setting datasets to an array which contains the datasetdata array. The code renders a result that looks as following:

datasets: [
    [ { dataset1 }, { dataset2 } ]
]

If you add select the value of the array at a specific index, you are extracting a single dataset from the datasetdata array.

var graphData = {
    labels: labels,
    datasets: [datasetdata[0]]
};

Your structure is then an array with a single dataset inside it:

datasets: [
   { dataset1 }
]

This code won't throw and error, since the structure is valid, however, it will only display the first result.

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