Highcharts add and remove Y axis plugin

by senthil_at

HTML

<script src="http://code.highcharts.com/stock/highstock.js"></script>
<script src="http://code.highcharts.com/stock/modules/exporting.js"></script>
<script type="text/javascript" src="http://www.highcharts.com/samples/data/usdeur.js"></script>
<div id="container" style="height: 300px"></div>

<button id="addaxis">1. Add Y axis</button>
<button id="addseries">2. Add series</button>
<button id="removeseries">3. Remove primary series</button>
<button id="removeaxis">4. Remove primary axis</button>

JavaScript

/*
 * Highcharts plugin for adding an axis after render time. Works with Highcharts >= 2.2.4.
 * As of Highcharts 3.0, the contents of this plugin will be part of the Highcharts
 * core.
 * Author: Torstein Hønsi
 * License: MIT License
 * Last revision: 2013-02-14
 */
(function (Highcharts) {
    
    var each = Highcharts.each,
        UNDEFINED;
    
    /**
     * Utility function to remove last occurence of an item from an array
     * @param {Array} arr
     * @param {Mixed} item
     */
    function erase(arr, item) {
        var i = arr.length;
        while (i--) {
            if (arr[i] === item) {
                arr.splice(i, 1);
                break;
            }
        }
        return i;
    }
    /**
     * Add an axis to the chart
     * @param {Object} options The axis option
     * @param {Boolean} isX Whether it is an X axis or a value axis
     */
    Highcharts.Chart.prototype.addAxis = function (options, isX) {
        var key = isX ? 'xAxis' : 'yAxis',
            axis = new Highcharts.Axis(this, Highcharts.merge(options, {
                index: chart[key].length
            }));
        
        // Push the new axis options to the chart options
        chart.options[key] = Highcharts.splat(chart.options[key] || {});
        chart.options[key].push(options);
    };
    
    /**
     * Remove an axis from the chart
     */
    Highcharts.Axis.prototype.remove = function () {
        if (this.series.length) {
            console.error('Highcharts error: Cannot remove an axis that has connected series');
        } else {
            var key = this.isXAxis ? 'xAxis' : 'yAxis';

            // clean up chart options
            var axisIndex = this.options.index;
            chart.options[key].splice(axisIndex, 1);
            
            erase(chart.axes, this);
            var index = erase(chart[key], this);
            
            // clean up following axis options (indices)
            for (var i = index; i < chart[key].length; i++)...