3

I am referring to this post on Stack Overflow:

Chart.js - draw horizontal line

The code mentioned in this post creates a horizontal line based on the location of a point on the graph. So say I had a point at 42 and a point at 44, then I could choose to put a line at either of those.

But in my current scenario, I want a point at 43 (for example), and this would be hard to draw as there is no "top value" for this point (the other two have top values calculated inside Chart.js). Is there a way to do this in Chart.js, for example, by calculating the "top value" needed for that line? In my actual graph I won't have points like 42 and 44 with which I can average and find 43, I'll have something more like 39 and 55, in which I need to draw a line at 43.

Community
  • 1
  • 1
Lucas
  • 16,930
  • 31
  • 110
  • 182

1 Answers1

3

Drawing a Horizontal Line at a Specific Y Value

Just utilize the scale.calculateY to do this

var data = {
    labels: ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"],
    datasets: [{
        data: [12, 3, 2, 1, 8, 8, 2, 2, 3, 5, 7, 1]
    }]
};

var ctx = document.getElementById("myChart").getContext("2d");
Chart.types.Line.extend({
    name: "LineWithYLine",
    draw: function () {
        Chart.types.Line.prototype.draw.apply(this, arguments);

        var scale = this.scale
        var ctx = this.chart.ctx;
        // calculate using the scale
        var y = scale.calculateY(this.options.lineAtValue);

        // draw line
        ctx.save();
        ctx.strokeStyle = '#ff0000';
        ctx.beginPath();
        ctx.moveTo(Math.round(scale.xScalePaddingLeft), y);
        ctx.lineTo(this.chart.width, y);
        ctx.stroke();
        ctx.restore();
    }
});

new Chart(ctx).LineWithYLine(data, {
    datasetFill: false,
    lineAtValue: 7.5
});

If you want to draw a label, you can adjust the line end position to leave space. Then use the same y value to draw text there.

If your chart data points don't cause the scale to stretch enough (eg. the scale is from 0 to 10, but you want to draw a line at 12) use the chart.js options to override the scale.


Fiddle - http://jsfiddle.net/gywzg9e4/

potatopeelings
  • 40,709
  • 7
  • 95
  • 119