Search code examples
javascriptc3.js

Plotting graph in C3.js using array


I have two arrays. One is of names (nameArray) and the other is of count(countArray). The values for the arrays will be obtained through an API.

var chart = c3.generate({
    bindto: '#chart',
    data: {
      columns: [
        ['data1', 30, 200, 100, 400, 150, 250]
      ]
    }
});

The above code sample is available from C3.js website . I need it to behave differently.

Sample arrays:-

nameArray=["name1","name2","name3"]
countArray=[20,34,12]

In this example , I want names to be along X-axis and count to be along Y-Axis. Please help me achieve this. Thanks


Solution

  • C3 has an option to accept Row Oriented Data:

    var chart = c3.generate({
    data: {
        rows: [
                ['data1', 'data2', 'data3'],
                [90, 120, 300],
                [40, 160, 240],
                [50, 200, 290],
                [120, 160, 230],
                [80, 130, 300],
                [90, 220, 320],
            ]
        }
    });
    

    Isn't that what you want? You just need to merge nameArray and countArray to array of arrays:

    var data = [];
    data.push(nameArray);
    //do this for each count array
    data.push(countArray);
    

    Then do:

    var chart = c3.generate({
        data: { rows: data }
    });
    

    Edit

    I think I follow you now. Is this what you want?

    In this case you need Category Axis feature. To prepare data you have to do the following:

    //your arrays
    var nameArray=["name1","name2","name3"]
    var countArray=[20,34,12]
    
    countArray.unshift('data');
    
    var chart = c3.generate({
        data: {
          columns: [countArray]
        },
        axis:{
          x:{
            type: 'category',
            categories: nameArray
          }
        }
    });