Using unknown number of datasets in Chart.js

不想你离开。 提交于 2019-12-24 08:23:44

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/44576156/using-unknown-number-of-datasets-in-chart-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!