Chartjs-Is there a way to insert multiple lines, with labels, dynamically, into a ChartJS Line chart?

0👍

I ended up doing something like this;

lineChartData = {}; //declare an object
lineChartData.labels = []; //add 'labels' element to object (X axis)
lineChartData.datasets = []; //add 'datasets' array element to object
var moreData = [[1, 3, 6, 16, 30, 6], [3,2,3,5,1,2], [3,11,23,2,1,9]];
function getLabels()
{
 var labels = ["one", "two", "three", "four", "five", "six"];  
 return labels;
}

for (line = 0; line < moreData.length; line++) {
    y = [];
    lineChartData.datasets.push({}); //create a new line dataset
    dataset = lineChartData.datasets[line]
    dataset.fillColor = "rgba(0,0,0,0)";
    if (moreData[line][0] == 1){
        dataset.strokeColor = "rgba(0,0,205,1)";
    } else {
        dataset.strokeColor = "rgba(200,200,200,1)";
    }
    dataset.data = []; //contains the 'Y; axis data

    for (x = 0; x < getLabels().length; x++) {
        labels = getLabels();
        for (var k = 0; k < moreData[line].length; k++){
        y.push( moreData[line][k]);
        }

        if (line === 0)
            lineChartData.labels.push(labels[x]);
    }

    lineChartData.datasets[line].data = y;
}

ctx = document.getElementById("Chart1").getContext("2d");
myLineChart = new Chart(ctx).Line(lineChartData);

4👍

Here’s a guess. I haven’t tried this, but based on the structure of the datasets, I’m thinking you can add a dataset to the array of data and then call update();

//here's the new dataset you want to add
var myNewDataset = {
        label: "My third dataset",
        fillColor: "rgba(151,187,205,0.2)",
        strokeColor: "rgba(151,187,205,1)",
        pointColor: "rgba(151,187,205,1)",
        pointStrokeColor: "#fff",
        pointHighlightFill: "#fff",
        pointHighlightStroke: "rgba(151,187,205,1)",
        data: [28, 48, 40, 19, 86, 27, 90]
    };

//push that onto the datasets array
lineData.datasets.push(myNewDataset);

//call the update method to render the new data
myLineChart.update();

Update method is described here: http://www.chartjs.org/docs/#line-chart-prototype-methods

1👍

You might want to use the Chart.Scatter extension (http://dima117.github.io/Chart.Scatter/). This is also linked to from the Chart.js documentation (see http://www.chartjs.org/docs/#advanced-usage-community-extensions)

Chart.Scatter supports date scales, which would get rid of the

At the moment, I’m going to work everything out manually (ie, get the
period specified by the user with jQuery, and run through the time
frame specified, counting the months and applying a label for each
one, then assigning values).

that you are doing (you’d still have to to reformat your data structure to fit in with the data structure expected by Chart.Scatter)

Leave a comment