Chartjs-How to change the angle of x axis ticks dynamically based on size of name?

0👍

You can dynamically change it in the chart config itself and then call update on the chart like so:

const options = {
  type: 'line',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
        label: '# of Votes',
        data: [12, 19, 3, 5, 2, 3],
        borderColor: 'pink'
      },
      {
        label: '# of Points',
        data: [7, 11, 5, 8, 3, 7],
        borderColor: 'orange'
      }
    ]
  },
  options: {
    scales: {
      x: {
        ticks: {
          minRotation: 0,
          maxRotation: 0
        }
      }
    }
  }
}

const ctx = document.getElementById('chartJSContainer').getContext('2d');
const chart = new Chart(ctx, options);

document.getElementById("switch").addEventListener("click", () => {
  chart.options.scales.x.ticks.minRotation = chart.options.scales.x.ticks.minRotation === 0 ? 90 : 0;
  chart.options.scales.x.ticks.maxRotation = chart.options.scales.x.ticks.maxRotation === 0 ? 90 : 0;
  chart.update();
});
<body>
  <button id="switch">
    Switch tick rotation
    </button>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.0/chart.js"></script>
</body>

Leave a comment