Render labels only when the data is available for a particular label

1👍

You can use the legend filter like this:

var options = {
  type: 'bar',
  data: {
    labels: ["Red", "Yellow", "Blue", "Yellow", "Green", "Purple", "Orange", "Green"],
    datasets: [{
        label: '# of Votes',
        data: [12, 19, 3, 5, 2, 0, 5, 6],
        borderWidth: 1,
        backgroundColor: 'red'
      },
      {
        label: '# of NonVotes',
        data: [],
        borderWidth: 1,
        backgroundColor: 'blue'
      }
    ]
  },
  options: {
    plugins: {
      legend: {
        labels: {
          filter: (legendItem, chartData) => (legendItem, chartData, chartData.datasets[legendItem.datasetIndex].data.length > 0)
        }
      }
    }
  }
}

var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.1.0/chart.js" integrity="sha512-LlFvdZpYhQdASf4aZfSpmyHD6+waYVfJRwfJrBgki7/Uh+TXMLFYcKMRim65+o3lFsfk20vrK9sJDute7BUAUw==" crossorigin="anonymous"></script>
</body>

Leave a comment