chartjs / Chart.js

Simple HTML5 Charts using the <canvas> tag
https://www.chartjs.org/
MIT License
64.75k stars 11.92k forks source link

Label of AxisY automatic line break #10202

Open sanhpotter opened 2 years ago

sanhpotter commented 2 years ago

Feature Proposal

As shown in the image below, I want to auto line break when the text exceeds the width of the Y axis. image

please show me how to make them. Thanks so much

Possible Implementation

No response

LeeLenaleee commented 2 years ago

You can implement this by using the tick callback:

const options = {
  type: 'line',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
      label: '# of Votes',
      data: [120000000000, 190000000000, 30000000000, 50000000000, 20000000000, 30000000000],
      borderColor: 'pink'
    }]
  },
  options: {
    scales: {
      y: {
        ticks: {
          callback: function(value) {
            const val = `${value}`
            return val.length > 4 ? `${val.substring(0, 4)}...` : val;
          }
        }
      }
    }
  }
}

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

https://jsfiddle.net/Leelenaleee/zfa4bwpg/5/

sanhpotter commented 2 years ago

@LeeLenaleee Thanks. I want it to be able to automatically line up when the text is too long like the example below.

https://jsfiddle.net/re5gd9p4/

LeeLenaleee commented 2 years ago

You can use an array to separate your label in multiline. Then you can use the crossAlign prop to make it the same as in your example.

You will need to calculate the splitting into the array yourself. Not sure if this is something that should live in the main lib.

https://jsfiddle.net/ktfouydv/