So far we have experimented with a lot of different graph options and configurations where themes defined a common set of styles; we may find a time where we have a very common type of graph that we want to create and we do not want to define the same options over and over again. We can avoid this tedium by creating reusable charts.
To get started, follow the ensuing instructions:
Determine what type of a chart you want to make reusable. Suppose that we want to take our existing spiderweb chart.
Create a new function
spiderWebChart
. This chart will take anoptions
argument to let us configure the chart and return aHighcharts.Chart
instance, as shown in the following code:var SpiderWebChart = function (options) { return Highcharts.Chart(options); };
Define default values for the chart that will give it the correct appearance, as we did in the recipe Creating spiderweb graphs for comparison, using the following code:
var SpiderWebChart = function (options) { // create options if they don't exist var modifiedOptions = options || {}; // create a chart option if it does not exist modifiedOptions.chart = modifiedOptions.chart || {}; modifiedOptions.chart.polar = true; // create an xAxis option if it does not exist modifiedOptions.xAxis = modifiedOptions.xAxis || {}; modifiedOptions.xAxis.tickmarkPlacement = 'on'; modifiedOptions.xAxis.lineWidth = 0; // create a yAxis option if it does not exist modifiedOptions.yAxis = modifiedOptions.xAxis || {}; modifiedOptions.yAxis.gridLineInterpolation = 'polygon'; modifiedOptions.yAxis.lineWidth = 0; return new Highcharts.Chart(modifiedOptions); };
Create a spiderweb graph using the options from the previously mentioned recipe, using the following code:
var chart = SpiderWebChart({ chart: { renderTo: 'container' }, title: { text: 'Creating spiderweb graphs for comparison' }, series: [{ name: 'Fighter', data: [10, 1, 5], pointPlacement: 'on' }, { name: 'Rogue', data: [5, 10, 1], pointPlacement: 'on' }] });
We have created a wrapper function for common options. Instead of using jQuery, we use the renderTo
option to find an element with container
as its ID and render the chart within that element. As we only overwrite certain properties in our SpiderWebChart
function, we can pass in as many other options as we like and only the ones relevant to the SpiderWebChart
function will be affected.