2014-01-28 80 views
11

我使用Chart.js来显示雷达图表。我的问题是有些标签很长: 图表无法显示或显示非常小。Chart.js和长标签

那么,有没有办法断开线条或为标签分配最大宽度?

谢谢你的帮助!

+0

请提供您的代码。 –

回答

0

看来你可能实际上是在谈论数据标签,而不是规模的标签。在这种情况下,您需要使用pointLabelFontSize选项。见下面的例子:

var ctx = $("#myChart").get(0).getContext("2d"); 

var data = { 
    labels: ["Eating", "Sleeping", "Coding"], 
    datasets: [ 
    { 
     label: "First", 
     strokeColor: "#f00", 
     pointColor: "#f00", 
     pointStrokeColor: "#fff", 
     pointHighlightFill: "#fff", 
     pointHighlightStroke: "#ccc", 
     data: [45, 59, 90] 
    }, 
    { 
     label: "Second", 
     strokeColor: "#00f", 
     pointColor: "#00f", 
     pointStrokeColor: "#fff", 
     pointHighlightFill: "#fff", 
     pointHighlightStroke: "#ccc", 
     data: [68, 48, 40] 
    } 
    ] 
}; 

// This is the important part 
var options = { 
    pointLabelFontSize : 20 
}; 

var myRadarChart = new Chart(ctx).Radar(data, options); 

最后你可能要与您的<画布的尺寸打>元素我发现有时给雷达图更高度有助于一切的自动缩放。

1

不幸的是,直到现在(2016年4月5日)还没有解决方案。 上有chart.js之多个问题来处理这个:

这是一种解决方法:Remove x-axis label/text in chart.js

24

对于chart.js之2.0+,您可以使用数组作为标签:

引用文档: “用法:如果一个标签,而不是一个字符串数组即[[ “六月”, “2015”], “月”]然后每个元素被视为一个单独的线。”

var data = { 
    labels: [["My", "long", "long", "long", "label"], "another label",...], 
    ... 
} 
+0

不是最干净的解决方案,但它为我工作。 –

+0

@Yeats - 上述解决方案适用于v2.3(垂直条形图,x轴刻度标签)。那么如何重新检查你的代码,而不是亵渎Arivan,这可能不是优雅的,但仍然功能的解决方案? – Ross

11

随着ChartJS 2.1.6和使用@ArivanBastos answer

只需将您的长标签传递给以下函数,它将以阵列形式返回您的标签,每个元素都将遵守您指定的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; 
} 
+0

真的很好!谢谢Fermin +1 – NickyTheWrench

+0

优秀,将它添加到项目中,核心或[插件](http://www.chartjs.org/docs/latest/developers/plugins.html) –

+0

顺便说一句,它也应该清楚,最大宽度“指字符而不是像素或任何其他测量 –