ChartJS - How to show a border on an empty pie chart?

I have a pair of pie / donut charts displayed with ChartJS . Usually they contain data like [200, 1200, 300] and [30, 500] for evaluation, but in rare cases they contain [0, 0, 0] and [0, 0] . The problem is that the chart disappears, although my border is on. I solved this problem by adding dummy values ​​to the first element in the arrays, but I don't like how the code looks, and I want a better way.

Is it possible to make the border visible (circle) when the array contains only zeros?

Edit: I am not getting any answers to this question. Is this considered an error when the border is not displayed on empty data, or is this the intended behavior? I don't know if anyone else had this problem. I still need to find an elegant way to deal with this problem, but I have not found it yet.

+9
source share
1 answer

This is not an error, since borders are displayed for each data item. If all the data is 0 s, then each slice has no width, so the borders are not displayed (the only other way to deal with this script for ChartJS is to give each element the same size, which is not better).

You can add a dummy value without a label and filter the legend and tooltips so that the data is treated as empty space for the user. In the example below, checking 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 without a label. Two data sets are shown to emphasize 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> 
0
source

Source: https://habr.com/ru/post/1263671/


All Articles