Understanding Highcharts – Categorized Series Data

This is a part of the Understanding Highcharts – Series Data blog series

Categories are a bunch of strings that sit on your independent (generally x) axis. Say, for plotting average temperature by country, the country names on the x-axis are categories. This is the simplest form of data, the points & x-axis labels are equally spaced horizontally.

Highcharts supports defining this kind of data in the following two ways

Method I – Using xAxis.categories

Defining the categories at once while defining the x-axis using the xAxis.categories option, and defining only the y values for each series

xAxis: {
	categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
},
series: [{
	name: 'Mumbai',
	data: [24.2, 24.6, 26.7, 28.6, 30.1, 29.0, 27.5, 27.2, 27.4, 28.2, 27.4, 25.6]
}, {
	name: 'New Delhi',
	data: [14.1, 16.9, 22.4, 28.6, 32.8, 33.8, 31.0, 29.8, 29.2, 26.0, 20.3, 15.4]
}]

Method II – Using {name,y} point format

If you are like me, you may not find the above approach very natural. The approach asked us to define all x-values (categories) first and then the y-values as another array, I prefer defining my points as (x,y) or something similar. Well, now we can do just that with Highcharts 3.0, which supports defining categories at the time of defining your data. The series.data now also takes an array of objects, with two properties viz. name and y. The name acts as the category. Additionally we need to instruct Highcharts to use the xAxis as a category axis as follows.

xAxis: {
	type: 'category'
},series: [{
	name: 'Mumbai',
	data: 	[{name:'Jan',y: 24.2},
		 {name:'Feb',y: 24.6},
		 {name:'Mar',y: 26.7},
		 {name:'Apr',y: 28.6},
		 {name:'May',y: 30.1},
		 {name:'Jun',y: 29.0},
		 {name:'Jul',y: 27.5},
		 {name:'Aug',y: 27.2},
		 {name:'Sep',y: 27.4},
		 {name:'Oct',y: 28.2},
		 {name:'Nov',y: 27.4},
		 {name:'Dec',y: 25.6}]
}]

Basic observation tells that the first method allows defining categories only once, hence if there are multiple series having same set of categories the first comes handy and prevents repetition & duplication. I would also use the first form if the set of categories were to be static, this would allow me to easily elevate the categories in a default option object. The second approach is more suited, in my opinion, for situations where the data and the categories are generated programmatically.

Read more @ Understanding Highcharts – Series Data blog series

Reference Links