change bar colors dynamically - highcharts

2019-08-21 08:16发布

问题:

I'm a R programmer trying to parse some JS code though highcharter package.

I'm trying to change each bar color on hover with this example based on this question.

I've tried this:

plotOptions: {
  column: {
    events: {
      mouseOver: function () {

        this.chart.series[this.index].update({
          color: 'blue'
        });
      },
      mouseOut: function () {

        this.chart.series[this.index].update({
          color: '#b0b0b0'
        });                           
      }
    };
    states: {
      hover: {

        color: colors[x]                                                           
      }
    }

  }
}

However I can only highlight with the 'blue' color. How can I use a different color for a different column?

Thank you.

回答1:

You see only the blue color on all columns, because you set those events on series. In order to achieve it, you can create arrays with colors and assign it to general chart object on chart.events.load. Then in series.point.events.mouseOver and mouseOut should be able to change the color by point index. Here is the example code:

highchart() %>% 
  hc_chart(events = list(
    load = JS("function() {this.customColors = ['red', 'green', 'blue']}")
  )) %>% 
  hc_series(
    list(
      data =  abs(rnorm(3)) + 1,
      type = "column",
      color = '#ddd',
      point = list(
        events = list(
          mouseOver = JS("function() {this.update({color: this.series.chart.customColors[this.index]})}"),
          mouseOut = JS("function() {this.update({color: '#ddd'})}")
        )
      )
    )
  )

API Reference:

https://api.highcharts.com/highcharts/series.column.point.events

https://api.highcharts.com/highcharts/chart.events.load