Search code examples
javascriptchartssplinetimeserieschartc3.js

C3js: custom date for each line


Is it possible to build data in this way?

['2013-01-01', 'redline', 120], 
['2013-01-02', 'greenline', 160], 
['2013-01-02', 'blueline', 200], 
['2013-01-04', 'greenline', 160], 

There is "n" count of different lines and each of them have different dates... How can I draw them with C3js? I will be really very appresiate any help


Solution

  • What you need is a line chart with multiple x axes, like this:

    enter image description here

    To use a multiple x chart in c3js, you must declare several xs values.

    I guessed you would need to add dates here and there, so I made the arrays containing data and dates global.

    The function at bottom pushes new dates and data to the arrays.

    To load those variables into c3js, use the concat function.

    //Declare three x axes, and a dataset for each axis.
    var periodOne = ['2013-01-01', '2013-01-04', '2013-01-07','2013-01-11','2013-01-15'];
    var periodTwo = ['2013-01-02', '2013-01-04', '2013-01-06','2013-01-08', '2013-01-10','2013-01-13', '2013-01-15','2013-01-18', '2013-01-22'];
    var periodThr = ['2013-01-05', '2013-01-10', '2013-01-15','2013-01-20', '2013-01-25'];
    var xOne = [12,31,14,13,34];
    var xTwo = [11,13,14,23,63,27,21,19,15];
    var xThr = [12,32,13,13,23];
    
    var chart = c3.generate({
            data: {
                xs:{
                    //Declare the axes
                    'Winter 08,09': 'x1',
                    'Winter 09,10': 'x2',
                    'Winter 10,11': 'x3'
                },
                columns: [
                    ['x1'].concat(periodOne),
                    ['x2'].concat(periodTwo),
                    ['x3'].concat(periodThr),
                    ['Winter 08,09'].concat(xOne),
                    ['Winter 09,10'].concat(xTwo),
                    ['Winter 10,11'].concat(xThr)
                ]
            },
            axis: {
                x: {
                    type: 'timeseries'
                }
            }
        });
    //You don't need this for multiple x axes, it's just to push data to arrays
    function push(oneValue, oneDate, twoValue, twoDate, thrValue, thrDate){
        periodOne[periodOne.length] = oneDate;
        xOne[xOne.length] = oneValue;
        periodTwo[periodTwo.length] = twoDate;
        xTwo[xTwo.length] = twoValue;
        periodThr[periodThr.length] = thrDate;
        xThr[xThr.length] = thrValue;
        chart.load({
            columns: [
                ['x1'].concat(periodOne),
                ['x2'].concat(periodTwo),
                ['x3'].concat(periodThr),
                ['Winter 08,09'].concat(xOne),
                ['Winter 09,10'].concat(xTwo),
                ['Winter 10,11'].concat(xThr)
            ]
        });
    }
    //Use this function to push new data
    push(13, '2013-01-19', 23, '2013-01-24', 17, '2013-01-30');