Hughesey
Hughesey

Reputation: 448

React-Chartjs-2 - How to make the label text stayed center wrapped?

I need the text in this graph to stay center wrapped but it goes horizontal instead. Had anyone had this issue with chartjs?

Picture of the graph

It works if you used a set amount of letters such as 'dummy'.

  datasets: {
    labels: ["Dummy text 1", "Dummy text 2", "Dummy text 3"],
    datasets: [
      {
        label: "",
        data: [13, 11, 2],
        backgroundColor: [
          "rgba(0, 135, 136)",
          "rgba(0, 193, 189)",
          "rgba(255, 9, 49)"
        ],
        borderColor: [
          "rgba(0, 135, 136)",
          "rgba(0, 193, 189)",
          "rgba(255, 9, 49)"
        ],
        borderWidth: 1
      }
    ]

Upvotes: 1

Views: 1806

Answers (2)

Aditi Pal
Aditi Pal

Reputation: 1

scales: {
  xAxes: [
    {
      ticks: {
        callback: function (label, index, labels) {
          if (/\s/.test(label)) {
            return label.split(' ');
          } else {
            return label;
          }
        }
      }
    }
  ]

This callback function will split your X Axis labels on the basis of space and arrange all the words in a wrapped manner. You can use the same function for Y axis values as well

Upvotes: 0

Hughesey
Hughesey

Reputation: 448

Fixed this easily with a multi-array and changing the xaxes. Here's the example fix -

  labels: [
  ["Dummy", "Data 1"],
  ["Dummy", "Data 2"],
  ["Dummy", "Data 3"]
],

 xAxes: [
        {
          ticks: {
            maxRotation: 0,
            minRotation: 0
          },
      }
  ]

Hopefully this helps someone out :)

Upvotes: 1

Related Questions