Search code examples
javascriptjsond3.jsc3.jsc3

Accessing data values in c3js in data events


I am trying to figure out, if there is a way to access the values from the Company data array in the onclick event. So far using the api functions I only get to the Users array.

var chartCompany = c3.generate({
    bindto: '#users-chart',        
    data: {
        x: 'Company',
        url: '/ajax_call',
        mimeType: 'json',
        type: 'bar',
        axes: {
            Company: 'x'
        },
        onclick: function (d, i) { console.log(chartCompany.data()); }
    },
    axis: {
        x: {
            type: 'category',
             show: false
        },
    }
});

And the json response from the server:

{
 "Company": ["Company 1", "Company 2", "Company 2"],
 "Users"  : [10, 20, 30]
}

Any help/ideas will be highly appreciated.

[Edit 1] To elaborate on my question: When clicking on a data from Users (which is displayed as bars) I would like to get the corresponding Company.

[Edit 2] Working static example: http://jsfiddle.net/et37a9t2/


Solution

  • After a lot of trying out different things, I finally just looked at the chart object itself and discovered a property categories. This is populated, when the x-axis is declared to be of type category as it is in my case. So to get the data from the x-axis one needs to call the .categories() function.

            ...
            },
            onclick: function (d, i) { console.log(chartCompany.categories()[d.index]); }
        },
        ...
    

    When clicking on a bar in the chart the corresponding category will be returned.