Search code examples
amcharts

How to remove a series from XYChartScrollbar in amCharts v4?


How can a series be removed from the XYChartScrollbar in amCharts v4?

It was added in much the same way as series are added to the chart:

chart.scrollbarX = new am4charts.XYChartScrollbar();
chart.scrollbarX.series.push(series);

Removing it seems to remove it from the List (chart.scrollbarX.series.length goes from 1 to 0) but it remains on the scrollbar display. I've also tried removeIndex, but no luck there either.

// removes from List, but still displayed
var scrollbarIndex = chart.scrollbarX.series.indexOf(series); 
chart.scrollbarX.series.removeIndex(scrollbarIndex);  

// same result, removed from List but still displayed
chart.scrollbarX.series.removeValue(series); 

I have also tried calling invalidate() and even deepInvalidate() to try to get the scrollbar to refresh but no success.

An example pen is at https://codepen.io/anon/pen/OrQvbw?editors=0011. Clicking on a toggle button adds the series to the chart and scrollbar, but only removes it from the chart.


Solution

  • Removing a series from the scrollbar itself does not seem to remove the series from the scrollbar's chart which itself is a whole other chart with distinct series. Going to look into this more and get back to you.

    In the meantime, we can piggy back off of the scrollbar's removeValue method via the series' List's "removed" event, to do the same thing on scrollbarChart. The scrollbarChart's series are all clones of the original chart's series, presuming a series only ever has 1 clone and that that clone is within scrollbarChart, this code seems to do the trick (removed.oldValue is the series we just removed from scrollbarX.series):

    chart.scrollbarX.series.events.on("removed", function(removed){
      chart.scrollbarX.scrollbarChart.series.removeValue(removed.oldValue.clones.getIndex(0));
    });
    

    Here's a fork of your demo with that addition:

    https://codepen.io/team/amcharts/pen/1b623a1b4ddf6a198bc80bdf5f5e1514