Slavi
Slavi

Reputation: 130

Y value minus 1 in tooltip HighCharts

I am struggling finding a way to return the previous Y value in the chart on the current Y value's tooltip. The idea is that I want to perform the action of "this.y - this.y(-1)" (getting that this.(y-1)) value and find the difference between the current and the one before that. Ideally, this will be in the tooltip for each of the values in the chart

My code is as follows:

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">


<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.js"></script>
<script src="https://code.highcharts.com/stock/highstock.js"></script>
<script src="https://code.highcharts.com/stock/modules/exporting.js"></script>
<script src="https://code.highcharts.com/modules/data.js"></script>

<div id="container" style="height: 500px; min-width: 310px"></div>

<script type="text/javascript">
    $(function () {
    $.get("data.csv", function (csv) {
        $('#container').highcharts('StockChart', {
            title: {
                text: 'Testing HighCharts'
            },
            data: {
                csv: csv
            },
            rangeSelector: {
                selected: 1
            },
            tooltip: {
                formatter:function(){
                        return '<b>Date:</b> ' + Highcharts.dateFormat('%B %e %Y', this.x) + '<br>' + '<b>Amount:</b> ' + this.y + '<br>';
                    }
            },
            plotOptions: {
                series: {
                    marker: {
                       enabled: true,
                       fillColor: 'FFFFFF',
                       radius: 4
                    },
                    allowPointSelect: true,
                    color: '#CC0000',
                    width: 3
                }
            }
        });
    });
});
</script>


</head>
</html>

Upvotes: 0

Views: 370

Answers (1)

Alex-ua
Alex-ua

Reputation: 36

You need to use index and series properties of this.point object inside the tooltip formatter.

tooltip: {
    formatter:function(){
        var diffText = '',
            i = this.point.index;

        if (i > 0) {
            diffText = '<br><b>Difference: </b>' + (this.y - this.point.series.data[i-1].y);
        }

        return '<b>Date:</b> ' + Highcharts.dateFormat('%B %e %Y', this.x) + '<br>' + '<b>Amount:</b> ' + this.y + '<br>' + diffText;
    }
},

Here is the demo: https://jsfiddle.net/alex_ua/7u80r0c3/2/

Upvotes: 1

Related Questions