Yujun Wu
Yujun Wu

Reputation: 3012

Make x label horizontal in ChartJS

enter image description here

Drawing a line chart with ChartJS 1.0.1 as above. As it shows, the label in the x-axis is not horizontal although there are enough space. How can I make it horizontal?

A side question, noticed the y label, there are 1-2px clipped. How to fix that?

Upvotes: 16

Views: 24993

Answers (4)

Anirudh
Anirudh

Reputation: 3358

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
            }
        }
    }
  };

Upvotes: 0

GMKHussain
GMKHussain

Reputation: 4681

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/[email protected]/dist/chart.min.js"></script>
<canvas id="myChart" width="400" height="400"></canvas>

Upvotes: 2

tabetomo
tabetomo

Reputation: 2711

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

Upvotes: 46

vnbt
vnbt

Reputation: 39

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;
        }
    ...
},

Upvotes: 1

Related Questions