2016-09-14 50 views
2

我想使用Charts.js v2库设置条形图。chart.js不同的x轴和工具提示格式

我遇到的问题是我想格式化X轴标签不同的工具提示标签。例如,如果我在x轴上有一个标签,例如“超长标签将被裁剪”,下面的代码将显示为“超长标签...”。

Chart.scaleService.updateScaleDefaults('category', { 
    ticks: { 
    callback: function(tick) { 
     var characterLimit = 20; 
     if (tick.length >= characterLimit) { 
      return tick.slice(0, tick.length).substring(0, characterLimit -1).trim() + '...';; 
     } 
     return tick; 
    } 
    } 
}); 

完全小提琴:https://jsfiddle.net/kvszjr7g/3/

这正常工作。

但是,将鼠标悬停在条上时显示的工具提示也会被修剪。我想要的是标签的全文显示在工具提示中。

我试过在上面的方法中使用字符串的副本,这就是为什么我添加了tick.slice。无论我已经尝试达到这一点,总是会影响x轴标签和工具提示标签。

我很迷茫,在这一点上,最好的方法是什么?

回答

8

首先,你最好直接从图表的选项编辑图表属性,而不是在大规模的服务为你这样做,它不会影响你的每个页面上的图表(如果你有几个) 。

要达到什么样的你已经做了,加你使用的功能在你的选择:

options: { 
    scales: { 
     xAxes: [{ 
      ticks: { 
       callback: function(tick) { 
        var characterLimit = 20; 
        if (tick.length >= characterLimit) { 
         return tick.slice(0, tick.length).substring(0, characterLimit - 1).trim() + '...'; 
        } 
        return tick; 
       } 
      } 
     }] 
    }, 
} 

它基本上是什么显示为您xAxe标签编辑。


但是,我们仍然有同样的问题:标签和工具提示都显示修剪过的字符串。

要解决它,你还需要编辑提示的回调:

options: { 
    // other options here, `scales` for instance 
    // ... 
    tooltips: { 
     callbacks: { 

      // We'll edit the `title` string 
      title: function(tooltipItem){ 
       // `tooltipItem` is an object containing properties such as 
       // the dataset and the index of the current item 

       // Here, `this` is the char instance 

       // The following returns the full string 
       return this._data.labels[tooltipItem[0].index]; 
      } 
     } 
    } 
} 


你可以看到一个完整的例子 in this jsFiddle这里是它的结果:

enter image description here

+0

感谢您的回答。也有关于我的问题在github上https://github.com/chartjs/Chart.js/issues/3311#issuecomment-247474334 – dlearious