Skip to content

Commit

Permalink
Fix trend line writing over axis.
Browse files Browse the repository at this point in the history
Fixes #21
  • Loading branch information
hailwood authored Nov 21, 2019
1 parent d4875d2 commit 609e9eb
Showing 1 changed file with 22 additions and 1 deletion.
23 changes: 22 additions & 1 deletion src/chartjs-plugin-trendline.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,27 @@ function addFitter(datasetMeta, ctx, dataset, xScale, yScale) {
var y1 = yScale.getPixelForValue(fitter.f(fitter.minx));
var y2 = yScale.getPixelForValue(fitter.f(fitter.maxx));
if ( !xy ) { x1 = startPos; x2 = endPos; }

const drawBottom = datasetMeta.controller.chart.chartArea.bottom;
const chartWidth = datasetMeta.controller.chart.width;

if(y1 > drawBottom) { // Left side is below zero
const diff = y1 - drawBottom;
const lineHeight = y1 - y2;
const overlapPercentage = diff / lineHeight;
const addition = chartWidth * overlapPercentage;

y1 = drawBottom;
x1 = (x1 + addition);
} else if(y2 > drawBottom) { // right side is below zero
const diff = y2 - drawBottom;
const lineHeight = y2 - y1;
const overlapPercentage = diff / lineHeight;
const subtraction = chartWidth - (chartWidth * overlapPercentage);

y2 = drawBottom;
x2 = chartWidth - (x2 - subtraction);
}

ctx.lineWidth = lineWidth;
if (lineStyle === "dotted") { ctx.setLineDash([2, 3]); }
Expand Down Expand Up @@ -96,4 +117,4 @@ LineFitter.prototype = {
var scale = (this.count * this.sumXY - this.sumX * this.sumY) / det;
return offset + x * scale;
}
};
};

0 comments on commit 609e9eb

Please sign in to comment.