How do I show labels along with lines in Chart.js v3?

๐Ÿ‘:0

Update added property clip: false, so that the labels a visible outside the chartArea (link to the documentation)

Out-of-the-box it is not possible as far as I know, but you could use a chart.js plugin like https://www.chartjs.org/chartjs-plugin-annotation/2.0.0/

Here a demo, how I would do this:

(You would have to tweak the position of the labels, check the documentation fr details)

const data = {
    labels: [1,2,3,4,5], 
    datasets: [{
        label: 'line-1',
        borderColor: '#36A2EB',
        backgroundColor: '#36A2EB',
        data: [50, 150, 180, 160, 100],
     },{
        label: 'line-2',
        borderColor: '#FF6384',
        backgroundColor: '#FF6384',
        data: [20, 110, 80, 190, 20],
     }
    ],
};

const config = {
     type: 'line',
    data: data,
    options: {
        maintainAspectRatio: false,
        plugins: {
            legend: {
                position: 'right',
            },
        
            annotation: {
              clip: false, // <-- Adding this property you can draw outside of the chart area
              annotations: {
                // Create them static
                label1: {
                  type: 'label',
                  xValue: 2,
                  yValue: 100,
                  backgroundColor: '#ffffff',
                  color: 'red',
                  content: ['static label'],
                
              }
            }
         }
      }
    }
};

// create them dynamic
data.datasets.forEach((item, index) => {
     config.options.plugins.annotation.annotations[item.label] = {
         type: 'label',
         xValue: data.labels.length-1.5,
         yValue: item.data[item.data.length-1],
         backgroundColor: '#ffffff',
         color: item.borderColor,
         content: [item.label],
         textAlign: 'start'
     }; 
})

new Chart(
    document.getElementById('chart'),
    config
);
<script src="//cdn.jsdelivr.net/npm/chart.js"></script>  
<script src="//cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-annotation/2.1.2/chartjs-plugin-annotation.min.js"></script>

<div class="chart" style="height:184px; width:350px;">
    <canvas  id="chart" ></canvas>
</div>

In this Demo Iโ€™m also showing how you could create the labels dynamically with the data from the chart, with this forEach loop. It is only a demo and would need some adjustments.

data.datasets.forEach((item, index) => {
   config.options.plugins.annotation.annotations[item.label] = {
     type: 'label',
     xValue: data.labels.length-1.5,
     yValue: item.data[item.data.length-1],
     backgroundColor: '#ffffff',
     color: item.borderColor,
     content: [item.label],
     textAlign: 'start'
   }; 
})

Leave a comment