Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Highcharts use series labels as x-axis categories

I have a simple 1-series highchart bar chart where I load the data using json. In my fiddle I just defined the json data as a static variable for simplicity but the premise is the same.

The json data forms the basis for all the series properties, including the name and is formatted like so, which is consistent to many examples I have seen:

var json = [{
    "name": "Currency Allocation",
    "data": [
        ["gbp", 0.7053985],
        ["usd", 0.17856322],
        ["eur", 0.06901525],
        ["chf", 0.00135777],
        ["jpy", 0.00815169],
        ["em_asia", 0.02821377],
        ["other", 0.00982446]
    ]
}];

I would like the label, which is the first element in each data sub-array to be the x-axis category for the chart. However, I seem to have to define the x-axis categories separately under cht.xAxis.categories. Is there a way to avoid doing this and just use the categories in my data?

If I exclude the xAxis.categories property the chart is plotted with just numbers on the x-axis

like image 719
harryg Avatar asked Jun 18 '14 15:06

harryg


1 Answers

You can do this on a chart.events.load call and looping through the series[0].data values. Since you say you only have one series per chart I am also assuming you only have one xAxis as well. You would loop through your data like so:

var seriesData = this.series[0].data;
var tCategories = [];
for (i = 0; i < seriesData.length; i++) {
    tCategories.push(seriesData[i].name);
}
this.xAxis[0].setCategories(tCategories);

Live demo.

Less complex method is to define your xAxis.type as 'category':

"xAxis": {
    "type": "category"
},

Live demo.

like image 132
wergeld Avatar answered Sep 21 '22 01:09

wergeld