Chartjs-Levels is overlapping in angular-chart.js

1👍

That’s because Chart.js shows all x axis labels and doesn’t drop them if the overlap. There is a feature request out there for this https://github.com/nnnick/Chart.js/pull/897 – which is still open.

There is also a separate branch – https://github.com/nnnick/Chart.js/pull/521 which solves the issue. But, it hasn’t been integrated into the main branch yet and you might want to read the full thread before opting for this.


There is a workaround however. You can just opt to set everything except every nth label when you pass in the labels array, like this

labels: ["Jan 1", "Jan 2",... and lots of days ....].map(function (e, index) {
     return index % 5 ? "" : e;
})

Adjust the value 5 as needed. The best way would be to adjust this based on the size of the array to get x number of points or less if the number of points crosses a threshold. e.g. if you want no more than 10 points, replace 5 with size of array / 10 IF size of array > 200 or at whichever point the overlaps start. Just make sure you don’t end up with too less markers :-). For instance, if you pick 30 instead of 200 as the threshold, there will be times when you have only 3 markers for 30+ data points. Or you can choose to be more creative with your mapping function (for example, make sure that you have a label at the end of the scale, etc.)

Here is an example with just Chart.js. The same logic will work with angular-chart.js as well.

var myLabels = []
var myValues = []
for (var i = 0; i < 1000; i++) {
    myLabels.push("label" + i);
    myValues.push(Math.random() * 1000)
}

var data1 = {
    labels: myLabels,
    datasets: [{
        label: "My Dataset",
        fillColor: "rgba(244, 6, 6, 1)",
        data: myValues
    }]
};

var ctx = document.getElementById("chart1").getContext("2d");
window.weeksChart = new Chart(ctx).Bar(data1, {
    barShowStroke : false
});


var data2 = {
    labels: myLabels.map(function (e, index) {
         return index % 30 ? "" : e;
    }),
    datasets: [{
        label: "My Dataset",
        fillColor: "rgba(244, 6, 6, 1)",
        data: myValues
    }]
};

var ctx = document.getElementById("chart2").getContext("2d");
window.weeksChart = new Chart(ctx).Bar(data2, {
    barShowStroke : false
});

with HTML

<canvas id="chart1" width="651" height="335"></canvas>
<canvas id="chart2" width="651" height="335"></canvas>

And here is the corresponding fiddle – http://jsfiddle.net/2kvwndtq/

The downside is that if you want tooltips you have to override your tooltip function as well to show the spaces with the corresponding label and not blank.

Leave a comment