0

chart js how can I wrap legend labels text if there is more content?

enter image description here

code sandbox: legend maxline

chart.js: 3.6.0

react-chartjs-2: 4.3.1

Kanti vekariya
  • 667
  • 3
  • 13

2 Answers2

2

There is only one possible solution specifically for chartjs as chartjs does not support what you are asking.

you should extract label from data object like this

const limit = 10;
const suffix = "..";
const labels = [
  "Redssssssssssssssssssssssssssssssssssss",
  "Blue",
  "Yellow",
  "Green",
  "Purple",
  "Orange"
];

data.labels = labels.map((text) =>
  text.length < limit ? text : text.substring(0, limit) + suffix
);

It is not ideal. but this small hack can small your problem. the problem is that tooltip will also get truncated which ideally is not a good idea.

Robokishan
  • 146
  • 1
  • 10
0

You can set overall width. For example:

<Doughnut
  options={{
    responsive: true,
    plugins: {
      legend: {
        position: "right",
        maxWidth: 120, //add this line to limit width
        labels: {
          boxWidth: 20
        }
      },
      title: {
        display: true,
        text: "Chart.js Doughnut Chart"
      }
    }
  }}
  data={data}
/>
Yekmaz
  • 1
  • 1