0

How can I center the X-axis of a Chart.js (v2.8.0) line chart when there is only one X-axis value?

<span style="width:50%; display:inline-block;">
    <canvas id="myChart"></canvas>
</span>
<script>
var ctx = document.getElementById('myChart');
var myChart = new Chart(ctx, {
    type: 'line',
    data: {
        labels: ['Jan'],
        datasets: [
            { borderColor: 'green', data: [5], label: 'SET1' },
            { borderColor: 'red', data: [7], label: 'SET2' },
            { borderColor: 'blue', data: [3], label: 'SET3' }
        ]
    }
});
</script>

Line Chart Example

  • Does this answer your question? [Chartjs linechart with only one point - how to center](https://stackoverflow.com/questions/34225719/chartjs-linechart-with-only-one-point-how-to-center) – ty. Dec 10 '19 at 01:09

1 Answers1

0

See Chartjs linechart with only one point - how to center

You can add dummy labels to center your single point:

{
    type: 'line',
    data: {
        labels: ['', 'Jan', ''],
        datasets: [
            { borderColor: 'green', data: [null, 5, null], label: 'SET1' },
            { borderColor: 'red', data: [null, 7, null], label: 'SET2' },
            { borderColor: 'blue', data: [null, 3, null], label: 'SET3' }
        ]
    }
}

Or you can use the scatter chart type to manually specify the x coordinate of your points.

ty.
  • 10,924
  • 9
  • 52
  • 71
  • Thank you, Ian! I used the dummy labels/null values hack in the link you suggested. It's unfortunate Chart.js doesn't provide a simpler option to horizontally center single data points or an option to buffer all datasets. – TuAmigoAlejandro Dec 10 '19 at 18:44