ng2-charts and annotation plugin: annotations not visible after data update

454 Views Asked by At

I am creating a graph that updates with data from a REST API, using the ng2-charts library. I use the annotation plugin. The number of annotation changes, so changing an existing annotation is not enough - I need to be able to add/remove new annotations at runtime.

When I add annotations to the graph options at the beginning, annotations render just fine. But at runtime, after updating the data and updating the options object, no annotations can be seen.

Later, I add annotations to the options of the graph:

this.barChartOptions.annotation.annotations.push(
   {
                drawTime: 'beforeDatasetsDraw',
                type: 'box',
                xScaleID: 'x-axis-0',
                yScaleID: 'y-axis-0',
                xMin: tmpFirstBorder,
                xMax: tmpLastBorder,
                yMin: 0.5,
                yMax: 5,
                backgroundColor: 'rgba(71, 158, 245, 0.5)',
                borderColor: 'rgb(71,158,245)',
                onClick: function (e) {
                  console.log('Box', e.type, this);
                }
              }

And update the data afterwards so the chart gets redrawn:

 this.barChartOptions = this.barChartOptions;
 this.barChartData = tempChartData;

The graph gets redrawn fine, but no annotations are there.

I thought it might be a problem of the chart options not updating, so I tried to add an explicit update:

@ViewChild(BaseChartDirective) chart: BaseChartDirective;

[...]

this.chart.chart.update();

But to no avail.

Does anyone know how I can draw the annotations correctly? Thanks.

2

There are 2 best solutions below

0
On

this.barChartOptions.annotation.annotations

is not an array. It's another object like in the example

const options = {
  plugins: {
    autocolors: false,
    annotation: {
      annotations: {
        line1: {
          type: 'line',
          yMin: 60,
          yMax: 60,
          borderColor: 'rgb(255, 99, 132)',
          borderWidth: 2,
        }
      }
    }
  }
};

So to add a new annotation, you need to add an object and not push an array element. For example you get the number of annotations already in the object with

let annotationsCount = Object.entries(this.barChartOptions.annotation.annotations)

Then you can add a new element with

this.barChartOptions.annotation.annotations[annotationsCount] = yourNewAnnotationObject

annotationCount can be anything. It is just the key of the new object like line1 in the example Using the number of objects already inside is just a suggestion. BUT it has to be unique, otherwise you overwrite an existing and not adding a new one

0
On

You can try to set drawTime property

annotation: {
          drawTime: 'afterDatasetsDraw',
          annotations: [....]
        }