Nyxynyx
Nyxynyx

Reputation: 63687

Show Text on Clicking Two Points on Highcharts?

Given an existing Highcharts (in a React component using highcharts-react-official), how can we make it such that when the user clicks on 2 points on the chart, the difference in values between these 2 points will be calculated and shown on the chart in a text box?

To illustrate the desired result, below is an image that shows a green text box with the percentage difference in values after the user clicks on 2 points on the line chart.

How can we achieve this using Highcharts?

enter image description here

Upvotes: 0

Views: 95

Answers (1)

ppotaczek
ppotaczek

Reputation: 39139

That feature doesn't require any react logic. You only need to use click callback function for a point and addAnnotations method. Example:

  point: {
    events: {
      click: function() {
        const point = this;
        const chart = point.series.chart;
        const previousPoint = chart.clickedPoint;

        if (previousPoint) {
          chart.clickedPoint = null;

          chart.addAnnotation({
            shapes: [{
              type: 'path',
              strokeWidth: 1,
              stroke: 'red',
              dashStyle: 'dash',
              points: [{
                x: point.x,
                y: point.y,
                xAxis: 0,
                yAxis: 0
              }, {
                x: previousPoint.x,
                y: previousPoint.y,
                xAxis: 0,
                yAxis: 0
              }]
            }],
            labels: [{
              allowOverlap: true,
              format: 100 - (previousPoint.y * 100 / point.y) + '%',
              shape: 'rect',
              point: {
                x: (point.x < previousPoint.x ? point.x : previousPoint.x) +
                  Math.abs(point.x - previousPoint.x) / 2,
                y: (point.y < previousPoint.y ? point.y : previousPoint.y) +
                  Math.abs(point.y - previousPoint.y) / 2,
                xAxis: 0,
                yAxis: 0
              }
            }]
          });
        } else {
          chart.clickedPoint = this;
        }
      }
    }
  }

Live demo: http://jsfiddle.net/BlackLabel/gzcrp0x4/

API Reference: https://api.highcharts.com/class-reference/Highcharts.Chart#addAnnotation

Upvotes: 2

Related Questions