Search code examples
javascriptchart.jschartjs-plugin-annotation

ChartJS Annotation line on stacked bar chart


I cannot get the annotation line to work on a stacked Bar Chart.

Example JS Fiddle: https://jsfiddle.net/cledwyn/rd5q6Lsz/10/

I have the standard Annotation per https://www.chartjs.org/chartjs-plugin-annotation/latest/samples/charts/bar.html

const annotation2 = {
  type: 'line',
  scaleID: 'x',
  borderWidth: 3,
  borderColor: 'black',
  value: 8,
  label: {
    rotation: 'auto',
    position: 'start',
    backgroundColor: 'black',
    content: 'Line at x=Label 5',
    enabled: true
  }
};

but when I stack the bar charts

      scales: {
        xAxes: { stacked: true },
        yAxes: { stacked: true }
      },

then the annotation line just goes from one corner of the chart to the other.


Solution

  • When running your JSFiddle, you can see the following warning on the console.

    "No scale found with id 'x' for annotation 'annotation2'"
    

    Therefore, changing scales.xAxes to scales.x should solve part of your problem.

    scales: {
      x: { stacked: true },
      y: { stacked: true }
    }
    

    You'll further have to add missing labels to data.labels and adjust annotation2.value.

    Please take a look at your amended code below and see how it works.

    const labels = ['Label 1', 'Label 2', 'Label 3',  'Label 4', 'Label 5'];
    const data = {
      labels: labels,
      datasets: [{
        label: 'one',
        data: [14, 21, 4, 5, 7],
        backgroundColor: 'rgb(255, 99, 132)'
      }, {
        label: 'two',
        data: [1, 3, 2, 4, 5],
        backgroundColor: 'rgb(255, 199, 132)'
      }, {
        label: 'three',
        data: [7, 1, 9, 6, 7],
        backgroundColor: 'rgb(255, 99, 32)'
      }]
    };
    
    const annotation2 = {
      type: 'line',
      scaleID: 'x',
      borderWidth: 3,
      borderColor: 'black',
      value: 4,
      label: {
        rotation: 'auto',
        position: 'start',
        backgroundColor: 'black',
        content: 'Line at x=Label 5',
        enabled: true
      }
    };
    
    const config = {
      type: 'bar',
      data: data,
      options: {
        plugins: {
          annotation: {
            annotations: {
              annotation2,
            }
          }
        },
        scales: {
          x: {
            stacked: true
          },
          y: {
            stacked: true
          }
        },
      },
    };
    
    const chart = new Chart('chart', config);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.8.0/chart.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-annotation/1.4.0/chartjs-plugin-annotation.min.js"></script>
    <canvas id="chart" height="110"></canvas>