Manage multiple highchart charts in a single webpage

后端 未结 3 771
滥情空心
滥情空心 2020-11-27 12:29

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,



        
3条回答
  •  一个人的身影
    2020-11-27 13:12

    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

    • http://api.highcharts.com/highcharts#Highcharts.setOptions%28%29

    COMPLETE DEMO

提交回复
热议问题