Search code examples
javascriptchartsaxislineserieslightningchart

In shared axis chart is it possible to hide the axis along with the series?


I am using LightningChartJS to create a chart. On clicking on the series description in the legend box the series disappears but the axis stays.Is it possible to hide the axis along with the series?

My axis and series are as follows :-

const axis1 = chart.getDefaultAxisY()
.setStrokeStyle(axisYStrokeStyles[0])
.setOverlayStyle(axisYStylesHighlight[0])
.setNibOverlayStyle(axisYStylesHighlight[0])
.setTickStyle(visibleTick => visibleTick
              .setLabelFillStyle(axisLabelStyle)
              .setGridStrokeStyle(emptyLine)
             )
const axis2 = chart.addAxisY(false)
.setTitle('No of units produced')
.setStrokeStyle(axisYStrokeStyles[1])
.setOverlayStyle(axisYStylesHighlight[1])
.setNibOverlayStyle(axisYStylesHighlight[1])
.setTickStyle(visibleTick => visibleTick
              .setLabelFillStyle(axisLabelStyle)
              .setGridStrokeStyle(emptyLine)
             )

             const splineSeries1 = chart.addSplineSeries({
  xAxis: axisX,
  yAxis: axisY1
})
const splineSeries2 = chart.addSplineSeries({
  xAxis: axisX,
  yAxis: axisY2
})

Solution

  • Yes, it's possible.

    When creating entries to the LegendBox

    const legendBox = chart.addLegendBox( LegendBoxBuilders.HorizontalLegendBox )
    // Add a single entry to the LegendBox. Since we know there is only one Entry, we can
    // cast the returned entry as one to avoid checking for Arrays.
    const entry = legendBox.add( series, true, splineSeries2.getName() ) as LegendBoxEntry
    

    You can subscribe to the onSwitch event to hide the corresponding Axis:

    // Subscribe to the onSwitch event.
    entry.onSwitch( ( _, state ) => {
      // The state parameter is the state of the CheckBox
      // If the CheckBox was just switched off, dispose of the Axis. Else, restore it.
      if ( !state ) {
        AxisY2.dispose()
      } else {
        AxisY2.restore()
      }
    })
    

    However, you should not dispose of the default Axes in this way, as there is no guarantee you'll have any other Axis in its place when you dispose it.