1

I'm using react-chartjs-2 v4.1 with ChartJS v3.8 in typescript.

I'd like to draw a horizontal line through my bar graph as shown below:

enter image description here

I find many half-written examples of which I cannot create a functional one. I couldn't find any complete, working example on how to use annotations.

My Code

I've added the chartjs-plugin-annotation package to my project.

Below is the code for a react component showing the graph of the screenshot. The annotation, however, does not work. Can anyone tell me what's wrong with the code?

import React from 'react';
import { Bar } from 'react-chartjs-2';

export const MyChart: React.FC = () => {
  const options2 = {
    plugins: {
      legend: {
        display: false,
      },
      annotation: {
        annotations: [
          {
            id: 'a-line-1',
            type: 'line',
            mode: 'horizontal',
            scaleID: 'y',
            value: 1.0,
            borderColor: 'red',
            borderWidth: 4,
            label: {
              enabled: false,
              content: 'Test label',
            },
          },
        ],
      },
    },
  };

   const data2 = {
    labels:   [ 'a', 'b'],
    datasets: [ { data: [1, 2] } ],
   };

   return (<Bar options={options2} data={data2} height={150} />
   );
};

DarkTrick
  • 2,447
  • 1
  • 21
  • 39

2 Answers2

1

You dont import and register the annotation plugin:

import { Chart } from 'chart.js';
import annotationPlugin from 'chartjs-plugin-annotation';

Chart.register(annotationPlugin);
LeeLenalee
  • 27,463
  • 6
  • 45
  • 69
  • AWESOME! I also had to set `type: 'line' as const` to silence typescript, so I created another answer for that. – DarkTrick Jun 08 '22 at 09:52
0

Based on LeeLenalee's answer here's a fully working example.

Changes to code in question:

  • import and register annotationPlugin
  • set annotation type to type: 'line' as const (not just type: 'line'). Otherwise typescript complains.
import React from 'react';
import { Bar } from 'react-chartjs-2';
import { Chart } from 'chart.js';
import annotationPlugin from 'chartjs-plugin-annotation';

Chart.register(annotationPlugin);


export const MyChart: React.FC = () => {
  const options2 = {
    plugins: {
      legend: {
        display: false,
      },
      annotation: {
        annotations: [
          {
            id: 'a-line-1',
            type: 'line' as const, // important, otherwise typescript complains
            mode: 'horizontal',
            scaleID: 'y',
            value: 1.0,
            borderColor: 'red',
            borderWidth: 4,
            label: {
              enabled: false,
              content: 'Test label',
            },
          },
        ],
      },
    },
  };

   const data2 = {
    labels:   [ 'a', 'b'],
    datasets: [ { data: [1, 2] } ],
   };

   return (<Bar options={options2} data={data2} height={150} />
   );
};
DarkTrick
  • 2,447
  • 1
  • 21
  • 39