Chart.js Plugin DataLabels example

by Shashi Kumar Nagulakonda

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.bundle.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels"></script>
<div style="position: absolute; left: 0px; top: 0px; right: 0px; bottom: 0px; overflow: hidden; pointer-events: none; visibility: hidden; z-index: -1;" class="chartjs-size-monitor">
  <div class="chartjs-size-monitor-expand" style="position:absolute;left:0;top:0;right:0;bottom:0;overflow:hidden;pointer-events:none;visibility:hidden;z-index:-1;">
    <div style="position:absolute;width:1000000px;height:1000000px;left:0;top:0"></div>
  </div>
  <div class="chartjs-size-monitor-shrink" style="position:absolute;left:0;top:0;right:0;bottom:0;overflow:hidden;pointer-events:none;visibility:hidden;z-index:-1;">
    <div style="position:absolute;width:200%;height:200%;left:0; top:0"></div>
  </div>
</div>

<canvas id="canvas_3" style="display: block; height: 322px; width: 645px;" width="1290" height="644" class="chartjs-render-monitor"></canvas>

JavaScript

var ctx = document.getElementById("canvas_3").getContext('2d');

var myChart = new Chart(ctx, {

  type: "bar",
  data: {
    labels: ["2009", "2010", "2011", "2012", "2013", "2014", "2015", "2016"],
    datasets: [{
        type: "line",
        label: "Deckungsgrad Anlagepool 1 in %",
        borderColor: "none",
        showLine: false,
        pointBackgroundColor: "#777",
        pointRadius: 5,
        data: [96.8, 95.9, 91.0, 95.2, 100.1, 105.9, 105.1, 106.0],
        fill: false,
        datalabels: {
          align: 'start',
          anchor: 'end',
          offset: 10,
          color: '#000',
        }
      },
      {
        type: "bar",
        label: "Deckungsgrad in %",
        backgroundColor: "rgba(232, 96, 34, 1)",
        borderColor: "rgba(232, 96, 34, 1)",
        backgroundColorHover: "rgba(232, 96, 34, 1)",
        data: [98.2, 97.7, 94.1, 98.0, 102.0, 107.0, 105.6, 105.9],
        datalabels: {
          align: 'end',
          anchor: 'start',
          offset: 0,
          color: '#fff'
        },
      }
    ]
  },

  options: {
    scales: {
      xAxes: [{}],
      yAxes: [{
        ticks: {
          stepSize: 10
        }
      }],

    },
    legend: {
      display: true,
      position: 'bottom',
      borderColor: 'transparent',
      borderWidth: 0,
      labels: {
        boxWidth: 20
      }
    },
    plugins: {
      datalabels: {
        color: 'black',
        display: function(context) {
          return context.dataset.data[context.dataIndex] > 0;
        },
        font: {
          weight: 'bold',
          size: '14'
        },
        // formatter: Math.decimals
      }
    },
  }
});