[Chartjs]-ChartJS – How to show border on empty pie chart?

8👍

This is not a bug, as the borders are rendered per data item. If all the data is 0s, then every slice has no width, so no border can show (the only other way to handle this scenario for ChartJS would be to give each item equal sizing, which isn’t better).

You can add a dummy value without a label and filter the legend and tooltips so that the data is treated like a blank space to the user. In the example below, a check before rendering the chart ensures that if all data points are 0, a data point with a value of 1 is added to the chart with no label. Two datasets are shown to highlight the difference.

let ctx = document.getElementById('chartContainer').getContext('2d');

let data = [[0, 0, 0], [1,2,3]];
let labels = ["A", "B", "C"];
let bgColors = ['yellow', 'orange', 'aquamarine'];

let options = {
  borderWidth: 1,
  borderColor: 'black',
  legend: {
    labels: {
    	// Prevent items with undefined labels from appearing in the legend
      filter: (item) => item.text !== undefined
    }
  },
  tooltips: {
    // Prevent items with undefined labels from showing tooltips
  	filter: (item, chart) => chart.labels[item.index] !== undefined
  }
}

let chartConfig = {
  type: 'pie',
  data: {
    labels: labels,
    datasets: [{
      data: data[0],
      backgroundColor: bgColors,
      label: "data",
      borderColor: 'black',
      borderWidth: 2
    }, {
      data: data[1],
      backgroundColor: bgColors,
      label: "data",
      borderColor: 'black',
      borderWidth: 2
    }]
  },
  options: options
}

// Check if data is all 0s; if it is, add dummy data to end with empty label
chartConfig.data.datasets.forEach(dataset => {
  if (dataset.data.every(el => el === 0)) {
    dataset.backgroundColor.push('rgba(255,255,255,0)');
    dataset.data.push(1);
  }
})


let pieChart = new Chart(ctx, chartConfig);
.chartContainer {
  height: 200px;
  width: 200px;
}
<script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0/dist/Chart.min.js"></script>
<div class="chartContainer">
  <canvas id="chartContainer" width="200" height="200"></canvas>
</div>

Leave a comment