问题
If I have 12 labels on a chart (one for each month), how can I just show the first 6 if other values are null ?
I use max: 'Jun'
for the moment but I'd like to automate this: when 'July' changes from null to a value, I'd like the max to become 'Jul'.
Is it possible with ChartJS ?
data: {
labels: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
datasets: [
{
spangaps: true,
label: 'Exceptionnel',
data: [1, 2, 3, 4, 5, 6, null, null, null, null, null, null]
},
options: {
scales: {
xAxes: [{
offset: true,
gridLines: {
display: true
},
ticks: {
fontStyle: 'bold',
max: 'Jun'
}
}]}],
回答1:
You can skip labels which have null values by checking in the callback
of ticks
like this.
<!DOCTYPE HTML>
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/chart.js@2.9.3/dist/Chart.min.js"></script>
</head>
<body>
<canvas id="myChart" width="200" height="200"></canvas>
<script>
var ctx = document.getElementById('myChart').getContext('2d');
let obj = {
labels: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
datasets: [{
spangaps: true,
label: 'Exceptionnel',
data: [1, 2, 3, 4, 5, 6, null, 5, null, null, null, null]
}]
};
var myChart = new Chart(ctx, {
type: 'bar',
data: obj,
options: {
scales: {
xAxes: [{
offset: true,
gridLines: {
display: true
},
ticks: {
callback: function (value, index, values) {
var dataValue = obj.datasets[0].data;
if (dataValue[index]) {
return values[index];
}
}
}
}]
}
}
});
</script>
</body>
</html>
回答2:
Check my answer here. You can simplify it:
var labels = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul"];
var data = [5, 6, 4, null, 5, null];
for (let i = 0; i <= data.length; i++){
if (data[i] === null) {
data.splice(i, 1);
labels.splice(i, 1);
i--;
}
}
However, if you are sure that once you reach a null value the rest are also null, you can splice not just one but the remaining as well. The trick is to also remove the labels so that no empty data is shown.
PS: I would advise not fetching labels with empty data from your back end if possible.
来源:https://stackoverflow.com/questions/62791870/skip-labels-when-associated-value-is-null-in-chartjs