Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chart.js and long labels

I use Chart.js to display a Radar Chart. My problem is that some labels are very long : the chart can't be display or it appears very small.

So, is there a way to break lines or to assign a max-width to the labels?

Thank you for your help!

like image 814
CedricParkerLewis Avatar asked Jan 28 '14 15:01

CedricParkerLewis


2 Answers

For Chart.js 2.0+ you can use an array as label:

Quoting the DOCs:

"Usage: If a label is an array as opposed to a string i.e. [["June","2015"], "July"] then each element is treated as a seperate line."

var data = {    labels: [["My", "long", "long", "long", "label"], "another label",...],    ... } 
like image 113
Arivan Bastos Avatar answered Oct 24 '22 19:10

Arivan Bastos


With ChartJS 2.1.6 and using @ArivanBastos answer

Just pass your long label to the following function, it will return your label in an array form, each element respecting your assigned maxWidth.

/* takes a string phrase and breaks it into separate phrases     no bigger than 'maxwidth', breaks are made at complete words.*/  function formatLabel(str, maxwidth){     var sections = [];     var words = str.split(" ");     var temp = "";      words.forEach(function(item, index){         if(temp.length > 0)         {             var concat = temp + ' ' + item;              if(concat.length > maxwidth){                 sections.push(temp);                 temp = "";             }             else{                 if(index == (words.length-1))                 {                     sections.push(concat);                     return;                 }                 else{                     temp = concat;                     return;                 }             }         }          if(index == (words.length-1))         {             sections.push(item);             return;         }          if(item.length < maxwidth) {             temp = item;         }         else {             sections.push(item);         }      });      return sections; } 
like image 45
Fermin Arellano Avatar answered Oct 24 '22 20:10

Fermin Arellano