简体   繁体   中英

Highcharts: show data labels as relative value (percentage) on hover

I'm trying to create a bar chart with a hover effect using Highcharts software. The chart should look like this: http://www.computerbase.de/2016-02/directx-12-benchmarks-ashes-of-the-singularity-beta/#diagramm-ashes-of-the-singularity-1920-1080

As you can see the data label values change into percentages once you hover the chart, showing the relative values.

Creating the chart itself is not the issue. Changing the data labels however is. How can I loop over all data labels, calculate the relative value and update the labels? The API does not say much.

$('#container').highcharts({
    chart: {
        type: 'bar'
    },
    plotOptions: {
        bar: {
            dataLabels: {
                enabled: true
            }
        },
        series: {
            point: {
                events: {
                    mouseOver: function() {
                        // change text of all data labels
                        console.log(this);
                        console.log(this.chart);
                    }
                }
            }
        }
    }
});

You may try this:

chart.tooltip.options.formatter = function() {
    var xyArr=[];
    $.each(this.points,function(){
        xyArr.push('Serie: ' + this.series.name + ', ' +'X: ' + this.x + ', Y: ' +this.y);
    });
    return xyArr.join('<br/>');
}

Example: http://jsfiddle.net/jugal/zAGGT/

It is possible to do Series.setData() with data that has new labels set on mouseOver event of point. Use dataLabels format option to get labels from point data and key setting in your series to set label info.

Example: http://jsfiddle.net/pov2dt0q/

$(function() {
  var startingData = [
      [1, '1'],
      [2, '2'],
      [3, '3']
    ],
    percentData = [
      [
        [1, 'x 100%'],
        [2, '200%'],
        [3, '300%']
      ],
      [
        [1, '50%'],
        [2, 'x 100%'],
        [3, '150%']
      ],
      [
        [1, '33%'],
        [2, '66%'],
        [3, 'x 100%']
      ]
    ];
  $('#container').highcharts({
    series: [{
      type: 'bar',
      dataLabels: {
        enabled: true,
        inside: true,
        align: 'right',
        x: -5,
        format: '{point.label}'
      },
      data: $.extend([], startingData),
      keys: ['y', 'label'],
      point: {
        events: {
          mouseOver: function() {
            this.series.setData(percentData[this.x]);
          },
          mouseOut: function() {
            this.series.setData(startingData);
          }
        }
      }
    }]
  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM