A little update using Chart.js v4.x and taking inspiration from another thread How do I change the colour of a Chart.js line when drawn above/below an arbitary value?, you can actually have different sections using different thresholds
My code to generate a dynamic plugin based on the values. I have min/max threshold and I consider the values inside as valid, while outside invalid.
You can just call the functions with the your parameters and add the plugin to the chart.plugins array when you create it.
cjs.get_color_line_plugin = function(t_min, t_max, valid_color, invalid_color) {
return {
id: 'color_line',
afterLayout: chart => {
const ctx = chart.ctx;
ctx.save();
const yScale = chart.scales["y"];
const y_min = yScale.getPixelForValue(t_min);
const y_max = yScale.getPixelForValue(t_max);
const gradientFill = ctx.createLinearGradient(0, 0, 0, chart.height);
gradientFill.addColorStop(0, invalid_color);
gradientFill.addColorStop(y_max / chart.height, invalid_color);
gradientFill.addColorStop(y_max / chart.height, valid_color);
gradientFill.addColorStop(y_min / chart.height, valid_color);
gradientFill.addColorStop(y_min / chart.height, invalid_color);
gradientFill.addColorStop(1, invalid_color);
const datasets = chart.data.datasets;
datasets.forEach(dataset => {
if (dataset.type == 'line') dataset.borderColor = gradientFill;
});
ctx.restore();
},
}
}
Result: (not too clear, but the line is darker above the threshold)