Chartjs-Chart.js Show Label near Line in combined Chart

0👍

The easiest way to do this is to use the chartjs-plugin-annotation plugin provided by the same team that provides chart.js.

You can use the plugin to draw arbitrary lines or boxes on your chart that can also contain a label. Unfortunately, the plugin does not yet support point annotations, so you have to use a little hack to enable the label to display but not the line or box.

Here is an example chart that uses the plugin to draw a horizontal white line at a specific Y value (white is used so that it blends in with the chart background and becomes invisible). The line is configured to also have a label. The end result is a text annotation on the chart with no visible line.

var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: ['Jan 21st', 'Feb 21st'],
    datasets: [{
      type: 'line', 
      label: 'B',
      data: [10, 25],
      fill: false,
      borderWidth: 3,
      borderColor: chartColors.orange,
      lineTension: 0,
    }, {
      type: 'bar',
      label: 'A',
      backgroundColor: chartColors.blue,
      data: [10, 25],
    }]
  },
  options: {
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }],  
      xAxes: [{
        ticks: {
          min: 'Jan 21st',
          max: 'Apr 21st',
        }
      }],
    },
    annotation: {
      annotations: [{
        type: 'line',
        mode: 'horizontal',
        scaleID: 'y-axis-0',
        value: 18,
        borderColor: 'white',
        borderWidth: 0,
        label: {
          xAdjust: -50,
          fontSize: 16,
          fontColor: 'black',
          backgroundColor: 'white',
          content: "+20%",
          enabled: true
        }
      }],
      drawTime: 'beforeDatasetsDraw'
    }
  }
});

You can see it in action at this codepen.

One final note, if you include the plugin in your app and you also use charts that don’t use scales (e.g. pie/doughnut) then you will get an error. This is a known issue and has been logged here.

The workaround is to add this to your pie/doughnut chart config (or it might be easier to add it to the pie/doughnut global default config).

scales:{
  yAxes: [],
  xAxes: []
},

Leave a comment