[Chartjs]-Make x label horizontal in ChartJS

46๐Ÿ‘

If you are using chart.js 2.x, just set maxRotation: 0 and minRotation: 0 in ticks options. If you want them vertical, set maxRotation: 90 and minRotation: 90 instead. And if you want to all x-labels, you may want to set autoSkip: false. The following is an example.

var myChart = new Chart(ctx, {
  type: 'bar',
  data: chartData,
  options: {
    scales: {
      xAxes: [{
        ticks: {
          autoSkip: false,
          maxRotation: 0,
          minRotation: 0
        }
      }]
    }
  }
});

example of 0 degree
enter image description here

example of 90 degree
enter image description here

2๐Ÿ‘

Use Rotation in scales > x > ticks

scales: {
   x: {
    ticks: {
      autoSkip: false,
      maxRotation: 90,
      minRotation: 90
    }
   }
}
let chart = new Chart('myChart', {

type: 'line',
    data: {
        labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
        datasets: [{
            label: '# of Votes',
            data: [12, 19, 3, 5, 2, 3]
        }]
    },
    options: {
        scales: {
            x: {
                ticks: {
                  autoSkip: false,
                  maxRotation: 90,
                  minRotation: 90
                }
            }
        }
    }
});
<script src="https://cdn.jsdelivr.net/npm/chart.js@3.6.2/dist/chart.min.js"></script>
<canvas id="myChart" width="400" height="400"></canvas>

1๐Ÿ‘

try fix the function calculateXLabelRotation in chart.js

calculateXLabelRotation : function(){
    ...
        //โ†“โ†“โ†“
        this.xLabelRotation = 0;
        //โ†‘โ†‘โ†‘
        if (this.xLabelRotation > 0){
            this.endPoint -= Math.sin(toRadians(this.xLabelRotation))*originalLabelWidth + 3;
        }
    ...
},

0๐Ÿ‘

Here is my options config

const options = {
    responsive: true,
    plugins: {
      legend: {
        position: 'top',
      },
      tooltip: {
        enabled: true
      },
    },
    scales: {
        xAxis: {
            ticks: {
                maxTicksLimit: 7,
                minRotation: 0,
                maxRotation: 0
            }
        }
    }
  };

Leave a comment