Search code examples
javascriptrhighchartsbar-chartr-highcharter

Set certain values of grouped variable in Highcharter bar plot to be deselected by default


I would like certain values of my grouped variable in a stacked Highcharter barplot to be deselected by default. I know that with hc_add_series I can set visible = FALSE but I am not generating my chart in that way.

Here is a sample data set:

responses <- c('Pro','Against','Neutral','Resigned/Accepting','Not Specified')
constituents <- c('dual degree','law only','undergrad only','friend','parent only')
indiv <- rep(1:50)
Name.Change <- sample(responses,50,replace = TRUE)
constituent.type <- sample(constituents,50,replace = TRUE)

demo <- as.data.frame(cbind(indiv,Name.Change,constituent.type))

And here is the chart

demo %>% 
  group_by(constituent.type,Name.Change) %>%
  summarise(count = n()) %>%
  hchart(type = "bar",
         hcaes(y = count,
               x = constituent.type,
               group = Name.Change)) %>%
  hc_plotOptions(bar = list(stacking = "percent")) %>%
  hc_tooltip(shared = TRUE)

The chart generated has all values of Name.Change selected and each value can be deselected as desired. However, I want certain values (e.g. "Neutral" and "Not Specified") to be deselected by default, such that after the chart is rendered, you would have to click that value in the legend in order for it to appear on the chart.


Solution

  • I think it's best to do it with chart.events.load, then you can write your own custom JS function for this: https://api.highcharts.com/highcharts/chart.events.load

    Here you can see how to do it:

    responses <- c('Pro','Against','Neutral','Resigned/Accepting','Not Specified')
    constituents <- c('dual degree','law only','undergrad only','friend','parent only')
    indiv <- rep(1:50)
    Name.Change <- sample(responses,50,replace = TRUE)
    constituent.type <- sample(constituents,50,replace = TRUE)
    demo <- as.data.frame(cbind(indiv,Name.Change,constituent.type))
    demo %>% 
      group_by(constituent.type,Name.Change) %>%
      summarise(count = n()) %>%
      hchart(type = "bar",
             hcaes(y = count,
                   x = constituent.type,
                   group = Name.Change)) %>%
      hc_chart(events = list(load = JS("function() {
      var chart = this;
      chart.series[1].setVisible(false)
      chart.series[2].setVisible(false)
      }"))) %>%
      hc_plotOptions(bar = list(stacking = "percent")) %>%
      hc_tooltip(shared = TRUE)