Search code examples
javascriptdiagramc3.js

How to build c3js line diagram from some function, not just simple array with random numbers?


I need to build a line diagram of some function (for example y=x*x). But how to pass the values of x and y to C3 columns?

Here I have the code, that build just a simple line diagram, so how do I need to modify it?

var chart = c3.generate({
data: {
    xs: {
        'data1': 'x1',
        'data2': 'x2',
    },
    columns: [
        ['x1', 10, 30, 45, 50, 70, 100],
        ['x2', 30, 50, 75, 100, 120],
        ['data1', 30, 200, 100, 400, 150, 250],
        ['data2', 20, 180, 240, 100, 190]
    ]
}
});

Solution

  • Why not just calculating some values and pushing it to your diagram? You only need one loop, calculate your data and push the results to the column. For example:

    var functionDataY = ['yLabel']
    var functionDataX = ['xLabel']
    
    for(var i=0; i<10; i++){
      functionDataY.push(i*i);
      functionDataX.push(i);
    }
    
    var chart = c3.generate({
    data: {
        xs: {
            'yLabel': 'xLabel',
        },
        columns: [
            functionDataY, functionDataX
        ]
    }
    });