[Chartjs]-Bar chart with min height and zero values โ€“ ChartJs

2๐Ÿ‘

โœ…

Is there a way to have a minimum bar length but exclude zero values or certain values in general?

ChartJS sees 0 as an value.

To let ChartJS know that that columns shouldnโ€™t be rendered, you should use NULL for the empty cols.

"data": [34, NULL, 1, NULL],

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.1/chart.min.js" integrity="sha512-QSkVNOCYLtj73J4hbmVoOV6KVZuMluZlioC+trLpewV8qMjsWqlIQvkn1KGX2StWvPMdWGBqim1xlC8krl1EKQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-datalabels/2.0.0/chartjs-plugin-datalabels.min.js" integrity="sha512-R/QOHLpV1Ggq22vfDAWYOaMd5RopHrJNMxi8/lJu8Oihwi4Ho4BRFeiMiCefn9rasajKjnx9/fTQ/xkWnkDACg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<canvas id=chart1 height="75"></canvas>
<script>
  let chart = document.getElementById('chart1').getContext('2d');
  var dataset = {
    "labels": ["OK", "Critical", "Warning", "Unknown"],
    "datasets": [{
      "label": "Example",
      "minBarLength": "40",
      "backgroundColor": ["rgba(58, 255, 0, 0.4)", 'rgba(255, 45, 0, 0.4)', 'rgba(255, 185, 0, 0.4)', 'rgba(161, 161, 161, 0.4)'],
      "borderColor": ["rgb(58, 255, 0)", 'rgb(255, 45, 0)', 'rgb(255, 185, 0)', 'rgb(161, 161, 161)'],
      "borderWidth": 2,
      "fill": true,
      "data": [34, null, 1, null],
    }]
  };
  var myChart = new Chart(chart, {
    plugins: [ChartDataLabels],
    type: 'bar',
    data: dataset,
    options: {

      indexAxis: 'x',
      scales: {
        y: {
          gridLines: {
            display: false
          },
          ticks: {
            display: false
          }
        }
      },
      plugins: {
        datalabels: {
          display: function(context) {
            return context.dataset.data[context.dataIndex] !== 0;
          },
          font: {
            size: 20,
          }
        },
        legend: {
          labels: {
            boxWidth: 0
          }
        }
      }
    }
  });
</script>

Leave a comment