Chart.js annotation plugin - Box not being displayed correctly

768 Views Asked by At

I'm using [email protected] and [email protected] in a Vue 2 project. I was able to build a chart with a line but the box is always expanded out to the edges, I'm not sure if the issue is related with my x-axis, since the values are strings (months).

import Chart from 'chart.js';
import AnnotationPlugin from 'chartjs-plugin-annotation';

Chart.plugins.register(AnnotationPlugin);

new Chart(lineChart.value, {
    type: 'line',
    data: {
      labels: [
        'January',
        'February',
        'March',
        'April',
        'May',
        'June',
        'July',
      ],
      datasets: [
        {
          label: 'Dataset 1',
          data: [120, 125, 128, 121, 130, 125, 135],
          borderColor: '#018572',
          backgroundColor: 'green',
          lineTension: 0.1,
          fill: false,
        },
        {
          label: 'Dataset 2',
          data: [81, 85, 88, 90, 83, 82, 80],
          borderColor: '#9F642C',
          backgroundColor: 'brown',
          lineTension: 0.1,
          fill: false,
        },
      ],
    },
    options: {
      title: {
        display: true,
        text: 'Chart.js Line Chart',
      },
      legend: {
        display: true,
        position: 'top',
        labels: {
          boxWidth: 80,
          fontColor: 'black',
        },
      },
      annotation: {
        annotations: [
          {
            drawTime: 'afterDraw',
            id: 'a-line-1',
            type: 'line',
            mode: 'horizontal',
            scaleID: 'y-axis-0',
            value: '25',
            borderColor: 'red',
            borderWidth: 2,
          },
          {
            type: 'box',
            drawTime: 'beforeDatasetsDraw',
            id: 'a-box-1',
            xScaleID: 'x',
            xMax: 'July',
            xMin: 'January',
            yScaleID: 'y',
            yMax: 140,
            yMin: 120,
            backgroundColor: 'green',
          },
        ],
      },
    },
  });

This is the result that I'm always getting:

I need to decrease the box in the y-axis since I need to show two bands in the chart. I'll really appreciate any help and suggestions.

1

There are 1 best solutions below

0
user2057925 On BEST ANSWER

I think the issue is related to xScaleID and yScaleID values. You set 'x' and 'y' as values but in chart.js 2, the default scales IDs are different. In fact, in the line annotation, you are setting 'y-axis-0'. That said, I think setting xScaleID: 'x-axis-0' and yScaleID: 'y-axis-0' should work.