Chart.js icon indicating copy to clipboard operation
Chart.js copied to clipboard

Line chart: manually limit x-axis tick labels

Open nielssj opened this issue 10 years ago • 3 comments

Hello, I'm building a line chart with a high number of data points (for the sake of example 10) and I would like to draw lines based on all 10 data points, but I would like to limit the number of x-axis tick labels to exactly 5 (every second data point). Here's the simplified version of what I'm trying to do:

var lineChart = new Chart(cnvLineChart, {
    type: 'line',
    data: {
        labels: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
        datasets: [
            {
                label: "Data set 1",
                data: [11, 22, 33, 44, 55, 66, 77, 88, 99, 100]
            },
            {
                label: "Data set 2",
                data: [111, 122, 133, 144, 155, 166, 177, 188, 199, 1100]
            }
        ]
    },
    options: {
        scales: {
            xAxes: [{
                ticks: {
                    stepSize: 2,
                    autoSkip: false
                },
                type: 'linear',
                position: 'bottom'
            }]
        }
    }
});

By default line chart uses categorical scale on the x-axis. But as far as I can understand I need a linear scale to get access to the ticks.stepSize option. However, when i set the type to linear as shown above, my script breaks and gets into an infinite rendering loop.

I searched through issues and found https://github.com/chartjs/Chart.js/issues/2228 where someone suggests to make a tick callback and return an empty string for every second tick. This works, but then I still end up with a really finely granulated grid, which I would prefer followed the tick labels.

Any idea how I can accomplish this?

nielssj avatar Apr 29 '16 13:04 nielssj

@nielssj in the callback if you return null or undefined the grid line will also be hidden

etimberg avatar Apr 29 '16 14:04 etimberg

Perfect, that works, thank you :)

nielssj avatar Apr 29 '16 14:04 nielssj

If you set a tick to be undefined or null using the tick callback, then you lose the ability to format the ticks as they show up when you hover over a point. Is there a way of dealing with this?

eatonphil avatar Mar 23 '17 20:03 eatonphil