Search code examples
javascriptrhighchartsr-highcharter

Clear chart by click in highcharts


I apologize for my English, I hope everything will be clear.

The question is: is it possible to make in highcharts so that when you click on the chart, the selection of all series is reset.

Now in more detail. I have graphs done using the R language package rCharts.

rCharts:

library(rCharts)

HideOtherSeriesOnClick <- function() {
  "#! function(event) {
   var selected = this.index;

   $.each(this.chart.series, function(index, series) {
      if (selected != index) {
         if (series.visible) {
            series.setVisible(false, false);
         } else {
            series.setVisible(true, false);
         }
      }
   });
   this.redraw();
   } !#"
}

HideMostSeriesByClickOnField <- function() {
  "#! function () {
   chart = this;
   var count_visibles = 0;

   $.each(chart.series, function(index, series) {
      if (series.visible) {
         count_visibles++;
      }
   });

   if (count_visibles < chart.series.length/2 ) {
      $(chart.series).each(function(){
         this.setVisible(true, false);
      });
      chart.redraw();
   } else {
      $(chart.series).each(function(){
         this.setVisible(false, false);
      });
      chart.redraw();
   }
}!#"
}

df <- data.frame(Wr.Hnd = c(18.5, 18, 19, 20, 21, 23, 4, 7, 5),
                 NW.Hnd = c(10, 12, 14, 9, 15, 12, 20, 23, 25),
                 Clap = rep(c("Right", "Left", "Center"), each = 3),
                 stringsAsFactors = FALSE)
#data <- MASS::survey
h1 <- hPlot(x = "Wr.Hnd", y = "NW.Hnd", data = df, type = "line", group = "Clap")
h1$chart( events = list(click = HideMostSeriesByClickOnField()))
h1$plotOptions(series = list( events = list(click = HideOtherSeriesOnClick())))
h1

Charts: enter image description here

Charts after one click on the plot: enter image description here

Charts after click on "Left" in legend: enter image description here

Now we are moving from rCharts to highcharter and we would like to keep this functionality. The problem is that these functions were written by another person, I do not know JS. Just copy-paste, of course, did not work. So my question is is it possible to implement something like this in highcharts and what should the code look like. Can be shown in pure JS in this example:

https://jsfiddle.net/t2MxW/21971/

Thanks in advance


Solution

  • I'm not sure if this is your requirement but I forked your fiddle here.

    I added an event on the chart using this

    chart: {
        renderTo: 'container',
        events: {
            click: function () {
               for(let i = 0; i < chart.series.length; i++){
                    chart.series[i].hide();
               }
            }
        }
    },
    

    so basically on click, all the chart series are hidden one by one. I used highcharts' documentation if you need references.