Chartjs-Chart.Js – Display only specific (fixed) X axis labels

1👍

Unfortunately your sample code does not show any data, so I had to make an assumption on how it might look like.

Within a vertical bar chart, individual bars get evenly spread among the available space on the x-axis. Therefore, the values for the x-axis (the labels) don’t matter in your case, their number only has to match the number of data values.

The number of data values however matters and it has to fit the linear scale. Therefore, in the runnable code snippet below, I provide 15 values (some of them are zero) and end up having 3 values for each section of 0.1 width.

const data = [0, 0.0003, 0.0008, 0.00025, 0.0012, 0.0018, 0, 0.00078, 0.00034, 0, 0, 0, 0, 0, 0];

var canvas = document.getElementById('myChart');
new Chart(canvas, {
    type: 'bar',
    data: {
        labels: data.map(v => 'x'),
        datasets: [{
            data: data,
            borderWidth: 2,
            borderColor: '#E16972',
            fill: false
        }]
    },
    options: {
        responsive: true,
        tooltips: {
            enabled: false
        },
        title: {
            display: false
        },
        legend: {
            display: false
        },
        scales: {
            yAxes: [{
                scaleLabel: {
                    display: true,
                    labelString: 'psd'
                },
                ticks: {
                    beginAtZero: true,
                    stepSize: 0.001
                }
            }],
            xAxes: [{
                    display: false
                },
                {
                    scaleLabel: {
                        display: true,
                        labelString: 'frequency'
                    },
                    type: 'linear',
                    ticks: {
                        max: 0.5,
                        stepSize: 0.1
                    }
                }
            ]
        }
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="myChart" height="80"></canvas>

Leave a comment