harryg
harryg

Reputation: 24107

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

Upvotes: 5

Views: 9230

Answers (1)

wergeld
wergeld

Reputation: 14462

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.

Upvotes: 8

Related Questions