Chartjs-How to write the value over each bullet in small div permanently in chart js

0👍

You can use the chartjs-plugin-datalabels plugin.

First you’ll have to register the plugin, then you can define the desired options inside options.plugins.datalabels.

If beside the value, you also want to display the corresponding label or some additional text, you need to define a formatter function.

Please take a look at the runnable code below and see how it works.

const chartLabels = ['2018', '2019', '2020', 'TTM'];
const priceToSaleRatioData = [3.37, 5.73, 1.88, 4.6];

Chart.register(ChartDataLabels);
new Chart('chart', {
  type: 'line',
  data: {
    labels: chartLabels,
    datasets: [{
      label: 'My Dataset',
      data: priceToSaleRatioData,
    }]
  },
  options: {
    plugins: {
      datalabels: {
        color: 'blue',
        anchor: 'end',
        align: 'top',
        formatter: (v, ctx) => {
          let label = ctx.chart.data.labels[ctx.dataIndex];
          if (label != 'TTM') {
            label = 'year ' + label;
          }
          return label + ': ' + v;
        }
      }
    },
    scales: {
      y: {
        max: 8
      },
      x: {
        offset: true
      }
    }
  }
});
datalabels: {
  formatter: function(value, context) {
    return context.chart.data.labels[context.dataIndex];
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.1/chart.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-datalabels/2.0.0/chartjs-plugin-datalabels.min.js"></script>
<canvas id="chart" height="100"></canvas>

Leave a comment