4

Using charts.js, chartjs-plugin-annotations and ng2-charts in angular 2 project, I need to annotate a line chart with a box annotation as in the figure bellow. enter image description here

Everything seems fine, except of the box annotations (red) that do not appear on the chart. The annotation related code are placed in chart options

annotation: {
     drawTime: 'beforeDatasetsDraw',
     annotations: [
        {
        type: 'box',
        id: 'y-axis-box',
        //mode: 'horizontal',
        yScaleID: 'y-axis-0',
        yMax: 2,
        yMin: 0,
        backgroundColor: 'red',
        //value: date,
        borderWidth: 2
        },
      {
        type: 'box',
        id: 'y-axis-1',
        //mode: 'horizontal',
        yScaleID: 'y-axis-0',
        yMax: 5,
        yMin: 4,
        backgroundColor: 'red',
        //value: date,
        borderWidth: 2
        }
    ]
  }

It appear that some extra configuration is required, mainly registering the plugin. The charts is drown using the baseChart directive from the imported ChartsModule in app.module.js

import {ChartsModule} from 'ng2-charts/ng2-charts';
hayordi
  • 119
  • 1
  • 8
  • 1
    I had to add ```require('chartjs-plugin-annotation');``` under my list of imports to register the plugin. – Jonath P Nov 19 '21 at 10:29

2 Answers2

2

It's not obvious but after installing npm install chartjs-plugin-annotation --save you should register it in yot Chart.js. You can do this directly in the component where you create the chart:

import { Chart } from 'chart.js';
import { default as Annotation } from 'chartjs-plugin-annotation';

  ngOnInit() {
    Chart.register(Annotation);
  }

Now you can use annotation features by putting them into the plugins section:

const chartOptions = {
  plugins: {
    annotation: {
      annotations: [{
        type: 'line',
        mode: 'horizontal',
        yMin: 6,
        yMax: 6,
      }]
    }
  }
};
-1

I'm not sure if annotations is not working with your ng2-charts setup at all, or it is just those red boxes that doesn't work for you. My answer will apply, getting the annotation plugin working.

Was facing the same issue, but found a working example. Obviously you need to install the annotation plugin:

npm install chartjs-plugin-annotation

After that you can copy the implementation demonstrated below directly.
Line Chart with annotation example

Just copy the Markup and TypeScript. Editing only 2 files, is enough.
No further configurations required. I just tested this working myself.

Dyhrberg
  • 7
  • 3
  • I just tested the annotations you provided in my own project. They work exactly as you expect. I think your problem is in your annotation setup, and then my answer should help you. – Dyhrberg Mar 24 '19 at 22:17
  • Check your annotation axis id. It must be the same name id of scale id. – Victor Oliveira Mar 17 '20 at 16:00