Using multiple Highcharts in a single page

2019-07-16 05:46发布

问题:

I’m using Highcharts and I want to add multiple charts to a single page

below is my js code

<script type="text/javascript">
$(function () {
    var chart;
    $(document).ready(function() {

        chart = new Highcharts.Chart({
            chart: {
                renderTo: 'container',
                plotBackgroundColor: null,
                plotBorderWidth: null,
                plotShadow: false
            },
            title: {
                text: 'Visual Data'
            },
            tooltip: {
                formatter: function() {
                    return '<b>'+ this.point.name +'</b>: '+ this.percentage +' %';
                }
            },
            plotOptions: {
                pie: {
                    allowPointSelect: true,
                    cursor: 'pointer',
                    dataLabels: {
                        enabled: true,
                        color: '#000000',
                        connectorColor: '#000000',
                        formatter: function() {
                            return '<b>'+ this.point.name +'</b>: '+ this.percentage +' %';
                        }
                    }
                }
            },

            series: [{

                type: 'pie', 
                name: 'Market Share',
                data: [
                    ['Plan 1',       <?php echo $1; ?>],
                    ['Plan 2',    <?php echo $2; ?>],
                    ['Plan 3',     <?php echo $3; ?>]

                ]
            }]
        });
    });

});
        </script>

I can simple repeat the code and change the code renderTo: 'container' to display the other charts but the code is duplicated many times.

Is there any better way that i can reuse the code so I can pass the data to

 series: []

title: {
                text: 'Visual Data'
            },

to display multiple charts. Currently I want to show 5 charts in a single page.

回答1:

You can use Highcharts.setOptions to define the options which are same for all the charts on the page. Following is the example code:

Highcharts.setOptions({
        global: {
            //Highchart uses UTC time by default
            useUTC: false
        },
        legend: {
            enabled: false
        },
        credits: {
            enabled: false
        },
        xAxis: {
            type: 'datetime',
            tickColor: '#96AA8C',
            labels: {
                style: {
                    color: '#555F50'
                }
            },
            tickPixelInterval: 70,
            maxZoom: 20 * 1000
        },
        title: {
            style: {
                color: '#343434'
            }
        },
        tooltip: {
            xDateFormat: '%d/%m/%Y %H:%M:%S'               

        }
    });

You can defined all the properties this way(Not sure about "All").