Chartjs-Display ellipsis for null or empty values in the bar chart using Chart.js

0👍

You can use of the Plugin Core API. It offers different hooks that may be used for executing custom code. In below code snippet, I use the beforeDraw hook to draw an ellipsis directly on the canvas when a value is zero.

new Chart('myChart', {
  type: 'bar',
  plugins: [{
    beforeDraw: chart => {
      let ctx = chart.chart.ctx;
      let xAxis = chart.scales['x-axis-0'];
      let yAxis = chart.scales['y-axis-0'];
      ctx.save();
      chart.data.labels.forEach((l, i) => {
        let value = chart.data.datasets[0].data[i];
        if (value == 0) {
          let x = xAxis.getPixelForValue(l);
          ctx.textAlign = 'center';
          ctx.font = '22px Arial';
          ctx.fillText('...', x, yAxis.bottom - 20);
        }
      });
      ctx.restore();
    }
  }],
  data: {
    labels: ['Jan', 'Feb', 'Mar'],
    datasets: [{
      label: 'My Dataset',
      data: [58, 0, 80],
      fill: false,
      backgroundColor: ['rgba(255, 99, 132, 0.2)', 'rgba(255, 159, 64, 0.2)', 'rgba(255, 205, 86, 0.2)'],
      borderColor: ['rgb(255, 99, 132)', 'rgb(255, 159, 64)', 'rgb(255, 205, 86)', 'rgb(75, 192, 192)'],
      borderWidth: 1
    }]
  },
  options: {
    legend: {
      display: false
    },
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        },
        gridLines: {
          display: false
        }
      }]
    }
  }
});
canvas {
  max-width: 200px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script>
<canvas id="myChart" height="150"></canvas>

Leave a comment