Manage multiple highchart charts in a single webpage

Selvaraj M A picture Selvaraj M A · Nov 24, 2011 · Viewed 47.7k times · Source

I am having multiple highchart charts of various types(Bar,Pie, Scatter type) in a single web page. Currently I am creating config object for each graph like,

{
chart : {},
blah blah,
}

And feeding them to a custom function which will just call HighCharts.chart(). But this results in duplication of code. I want to manage all this chart rendering logic centrally.

Any Idea on how to do this?

Answer

Ricardo Alvaro Lohmann picture Ricardo Alvaro Lohmann · Mar 7, 2012

You can use jQuery.extend() and Highcharts.setOptions.
So first you'll make the first object which will be extended by all your charts, this object will contain your Highchart default functions.

You can do it using namespacing.
The following way is good when you have very different charts.

Default graphic:

var defaultChart = {
    chartContent: null,
    highchart: null,
    defaults: {

        chart: {
            alignTicks: false,
            borderColor: '#656565',
            borderWidth: 1,
            zoomType: 'x',
            height: 400,
            width: 800
        },

        series: []

    },

    // here you'll merge the defauls with the object options

    init: function(options) {

        this.highchart= jQuery.extend({}, this.defaults, options);
        this.highchart.chart.renderTo = this.chartContent;
    },

    create: function() {

        new Highcharts.Chart(this.highchart);
    }

};

Now, if you want to make a column chart, you'll extend defaultChart

var columnChart = {

    chartContent: '#yourChartContent',
    options: {

        // your chart options
    }

};

columnChart = jQuery.extend(true, {}, defaultChart, columnChart);

// now columnChart has all defaultChart functions

// now you'll init the object with your chart options

columnChart.init(columnChart.options);

// when you want to create the chart you just call

columnChart.create();

If you have similar charts use Highcharts.setOptions which will apply the options for all created charts after this.

// `options` will be used by all charts
Highcharts.setOptions(options);

// only data options
var chart1 = Highcharts.Chart({
    chart: {
        renderTo: 'container1'
    },
    series: []
});

var chart2 = Highcharts.Chart({
    chart: {
        renderTo: 'container2'
    },
    series: []
});

Reference

COMPLETE DEMO