2👍
The solution provided by this answer can easily be adapted to also work with Chart.js v3.7.1.
Please take a look at below runnable code and see how it works.
const threshold = 25;
new Chart('myChart', {
type: 'line',
plugins: [{
afterLayout: chart => {
let ctx = chart.ctx;
ctx.save();
let yAxis = chart.scales.y;
let yThreshold = yAxis.getPixelForValue(threshold);
let gradient = ctx.createLinearGradient(0, yAxis.top, 0, yAxis.bottom);
gradient.addColorStop(0, 'green');
let offset = 1 / yAxis.bottom * yThreshold;
gradient.addColorStop(offset, 'green');
gradient.addColorStop(offset, 'red');
gradient.addColorStop(1, 'red');
chart.data.datasets[0].borderColor = gradient;
ctx.restore();
}
}],
data: {
labels: ['A', 'B', 'C', 'D', 'E', 'F', 'G'],
datasets: [{
label: 'My Dataset',
data: [32, 44, 29, 33, 18, 15, 30],
fill: false,
lineTension: 0.2
}]
},
options: {
plugins: {
legend: {
display: false
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.1/chart.min.js"></script>
<canvas id="myChart" height="80"></canvas>
- [Chartjs]-Chart.js is not rendered until zoom in in angular 8
- [Chartjs]-How to fix bar width in chartjs?
1👍
I have made a detailed response here that can help you.
Here is the code:
var myLineChart = new Chart(ctx, {
type: 'line',
plugins: [{
afterLayout: chart => {
let ctx = chart.chart.ctx;
ctx.save();
let yAxis = chart.scales["y-axis-0"];
let yThresholdMax = yAxis.getPixelForValue(data.limits.max);
let yThresholdMin = yAxis.getPixelForValue(data.limits.min);
let offsetMax = 1 / yAxis.bottom * yThresholdMax;
let offsetMin= 1 / yAxis.bottom * yThresholdMin;
let gradient = ctx.createLinearGradient(0, yAxis.top, 0, yAxis.bottom);
gradient.addColorStop(0, 'red');
gradient.addColorStop(offsetMax, 'darkred');
gradient.addColorStop(offsetMax, 'blue');
gradient.addColorStop(offsetMin, 'blue');
gradient.addColorStop(offsetMin,'darkred');
gradient.addColorStop(1,"red");
chart.data.datasets[0].borderColor = gradient;
ctx.restore();
}
}],
// The data for our dataset
data: {
......
},
options: {
........
}
});
- [Chartjs]-How to change size of point in ChartJS
- [Chartjs]-Scattered graph with xAxes of date react-chratjs-2
Source:stackexchange.com