How to display average line in chart.js?

by jasen_gottlieb , in category: Javascript , 9 months ago

How to display average line in chart.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by muriel.schmidt , 9 months ago

@jasen_gottlieb 

To display an average line in Chart.js, you can use the afterDraw method of the Chart instance to draw a horizontal line at the y-coordinate of the average value.


Here is an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
// Get the canvas element
var ctx = document.getElementById('myChart').getContext('2d');

// Define the average value
var averageValue = 50;

// Create the chart
var myChart = new Chart(ctx, {
    type: 'line',
    data: {
        labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
        datasets: [{
            label: 'My Dataset',
            data: [12, 19, 3, 5, 2, 3],
            fill: false,
            borderColor: 'rgb(75, 192, 192)',
            tension: 0.1
        }]
    },
    options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
            afterDraw: function(chart, easing) {
                var ctx = chart.chart.ctx;
                var xAxis = chart.scales["x"];
                var yAxis = chart.scales["y"];
                var linePosition = yAxis.getPixelForValue(averageValue);

                // Draw the average line
                ctx.beginPath();
                ctx.moveTo(xAxis.left, linePosition);
                ctx.strokeStyle = 'rgb(255, 0, 0)';
                ctx.lineTo(xAxis.right, linePosition);
                ctx.stroke();
            }
        }
    }
});


In this example, a line is drawn at the y-coordinate corresponding to the average value of 50. You can modify the averageValue variable to match your desired average.