Chartjs-ChartJS labels along the edges

0👍

You can use the axes callbacks to
set uncommon/not covered properties, but by doing so you forfeit some of the services and protections built in the scales code. In particular, if the chart is static and you are sure that tick labels will never overlap, you could use afterBuildTicks callback to set the ticks positions of a time scale – the position of a tick is its value property, in unix timestamp.

Here’s an example:

const d0 = new Date('2021-09-01').valueOf(),
    d1 = new Date('2023-09-10').valueOf(),
    N = 100;

const labels1 = Array.from({length: N}, (_, i) => {
    return d0 + (d1-d0)/(N-1)*i;
});
const data = {
    labels: labels1,
    datasets: [
        {
            label: 'Bars',
            data: Array.from({length: N}, (_, i) => Math.random() < 0.4 && i !== 0 && i !== N-1 ? 0 : 5 + Math.random() * 10),
            backgroundColor: 'rgba(128, 196, 32, 0.85)',
        },
        {
            label: 'Line',
            type: 'line',
            data: Array.from({length: N}, (_, i) => 5 + i/N * 10 + Math.random() / 2),
            fill: true,
            pointRadius: 0,
            backgroundColor: 'rgba(196, 196, 196, 0.5)',
        }
    ]
};

const config = {
    type: 'bar',
    data: data,
    options: {
        responsive: true,
        scales:{
            x:{
                type: 'time',
                grid: { display: false },
                time:{
                    unit: "day",
                    displayFormats: {
                        day: 'MMM yyyy'
                    }
                },
                  ticks: {autoSkip: true, maxTicksLimit: 5, //stepSize: (d1-d0)/4/3600/1000/24,
                    maxRotation: 0, minRotation: 0
                },
                min: d0 - 5*24*36e5, // add a margin of 5 days to make sure the data fits
                max: d1 + 5*24*36e5,

                afterBuildTicks(scale){
                    const nTicks = scale.options.ticks.maxTicksLimit ?? 10;
                    scale.ticks = Array.from({length: nTicks}, (_, i)=>({value: (d1-d0)/(nTicks-1)*i+d0}));
                }
            },
            y:{
                display: false
            }
        },
        plugins: {
            legend: {
                display: false
            },
            title: {
                display: true,
                text: ''
            }
        }
    },
};

new Chart('chart1', config);
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.4.0/chart.umd.js" integrity="sha512-6HrPqAvK+lZElIZ4mZ64fyxIBTsaX5zAFZg2V/2WT+iKPrFzTzvx6QAsLW2OaLwobhMYBog/+bvmIEEGXi0p1w==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

<script src="https://cdn.jsdelivr.net/npm/luxon@^3"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-luxon@^1"></script>

  <div style="min-height: 60vh">
    <canvas id="chart1">
    </canvas>
  </div>

Leave a comment