Chartjs-Render annotation in timeseries chart

2πŸ‘

βœ…

The issue is the average function. When you are using "data points" (objects as data), you have to use the property of the object which is representing the Y data.

function average(ctx) {
  const values = ctx.chart.data.datasets[0].data;
  // you have to use b.y to get the y value and not simply b which is an object
  return values.reduce((a, b) => a + b.y, 0) / values.length;
}

2πŸ‘

You should import the date adapter library as mentioned in the [documentation]

The time scale requires both a date library and a corresponding adapter to be present. Please choose from the available adapters.

<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-date-fns/dist/chartjs-adapter-date-fns.bundle.min.js"></script>

While in the annotation which you are drawing a line indicating the average,

b is an object, instead, I believe that you should get the value with b.y.

function average(ctx) {
  const values = ctx.chart.data.datasets[0].data;
  return values.reduce((a, b) => a + b.y, 0) / values.length;
}

Demo @ StackBlitz

Leave a comment