Skip to content

Instantly share code, notes, and snippets.

@fulldecent
Last active August 18, 2023 16:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fulldecent/e254dcdac0890194ef5423b10f1a96b1 to your computer and use it in GitHub Desktop.
Save fulldecent/e254dcdac0890194ef5423b10f1a96b1 to your computer and use it in GitHub Desktop.
Chart.js show line with green above target and red below
<!DOCTYPE html>
<html>
<head>
<title>Line Chart Example</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
<div style="width: 80%; margin: auto;">
<canvas id="myLineChart"></canvas>
</div>
<script>
// Sample data for the line chart
var data = {
labels: ["January", "February", "March", "April", "May"],
datasets: [
{
"label": "Target",
"data": [100, 100, 100, 100, 100],
// no dots
"pointRadius": 0,
},
{
label: "Our performance",
data: [130, 75, 180, 80, 70],
fill: false,
pointBackgroundColor: function(context) {
var value = context.parsed.y;
return value >= 100 ? 'green' : 'red';
},
pointBorderColor: function(context) {
var value = context.parsed.y;
return value >= 100 ? 'green' : 'red';
},
borderColor: "green", // for legend
segment: {
borderColor: function(context) {
const p0Value = context.p0.raw;
const p1Value = context.p1.raw;
var stopOffset = 0.5;
if (p0Value > 100 && p1Value < 100) {
// linearly interpolate the stop offset
stopOffset = (100 - p0Value) / (p1Value - p0Value);
} else if (p0Value < 100 && p1Value > 100) {
stopOffset = 1 - (100 - p1Value) / (p0Value - p1Value);
}
var gradient = context.chart.ctx.createLinearGradient(context.p0.x, context.p0.y, context.p1.x, context.p1.y);
gradient.addColorStop(stopOffset, p0Value >= 100 ? 'green' : 'red');
gradient.addColorStop(stopOffset, p1Value >= 100 ? 'green' : 'red');
return gradient;
},
}
}]
};
// Chart configuration
var options = {
responsive: true,
maintainAspectRatio: false,
scales: {
y: {
beginAtZero: false,
}
}
};
// Create the line chart
var ctx = document.getElementById("myLineChart").getContext("2d");
var myLineChart = new Chart(ctx, {
type: 'line',
data: data,
options: options
});
</script>
</body>
</html>
@fulldecent
Copy link
Author

Screenshot 2023-08-18 at 12 07 36

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment