Search code examples
javascripthighchartsaxes

Highcharts: Add a button on the chart to hide or show multiple axes


I have a chart that has 3 y-axes. I have a requirement where the user has the option to show or hide the y-axis on the chart but I need some help getting it to work.

I have added a button on the chart and have tried two different things to get the axis to hide: (i) Use the show and hide methods on the axis (which produces a console error) (ii) Set the visible property to trye and false.

Here is the code I have for the button:

exporting: {
            buttons: {
                customButton: {
                    text: 'Hide/Show Y-Axis',
                    onclick: function () {

                       /* 
                       /// I get a console error trying to use the hide or show method
                       this.yAxis[0].visible ? this.yAxis[0].hide() : this.yAxis[0].show();

                          */ 

                    if (this.yAxis[0].visible || this.yAxis[1].visible || this.yAxis[2].visible)
                    {
                    this.yAxis[0].visible = false;
                    this.yAxis[1].visible = false;
                    this.yAxis[2].visible = false;
                    }
                    else
                    {
                    this.yAxis[0].visible = true;
                    this.yAxis[1].visible = true;
                    this.yAxis[2].visible = true;
                    } 

               this.redraw();

                    }
                } 
            }
        }

This seems to do something when it gets to this.redraw() but its not hiding the axes. What am I doing wrong here?

Complete code: JSFiddle

Thanks


Solution

  • You need to use the update method on the axes with the new visible state

    Here is the update onclick code:

    exporting: {
        buttons: {
          customButton: {
          text: 'Hide/Show Y-Axis',
          onclick: function() {
            this.yAxis.forEach((axis) => {
              axis.update({
                visible: !axis.visible
              })
            })
          }
        }
      }
    }
    

    Updated fiddle: https://jsfiddle.net/8tmvjbhu/2/