javascript 在 ChartJS 中截断画布标签,同时在工具提示中保留完整标签值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28296994/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Truncating canvas labels in ChartJS while keeping the full label value in the tooltips
提问by Norbert
I have some bar charts that have really long labels and they affect the size of the charts.
我有一些条形图的标签很长,它们会影响图表的大小。
Example: http://jsfiddle.net/norbiu/aqa8w19d/4/
示例:http: //jsfiddle.net/norbiu/aqa8w19d/4/
I'm trying to truncate the labels that show up under the chart while keeping the label that shows up in the tooltips when hovering over a bar. The problem is that the tooltips and the canvas labels both get their values from the labels
array in the data structure. Truncating the value will show the shortened version in both locations.
我试图截断显示在图表下方的标签,同时保留将鼠标悬停在条形图上时显示在工具提示中的标签。问题是工具提示和画布标签都从labels
数据结构中的数组中获取它们的值。截断该值将在两个位置显示缩短的版本。
sales: ko.observable({
labels: ['A really really long label', 'Another long labe', 'A third label that is long', 'Q4', 'Q5', 'Q6'],
datasets: [{
label: 'Helados',
fillColor: '#152491',
data: [70, 32, 6, 23, 63, 43]
}]
}),
The documentation has nothing on this. Any ideas?
文档对此没有任何说明。有任何想法吗?
回答by ursuleacv
In Chart JS V2 you can truncate labels passing the options object. Also you can customize the tooltips.
在 Chart JS V2 中,您可以截断传递选项对象的标签。您也可以自定义工具提示。
options:{
scales: {
xAxes: [{
ticks: {
callback: function(value) {
return value.substr(0, 10);//truncate
},
}
}],
yAxes: [{}]
},
tooltips: {
enabled: true,
mode: 'label',
callbacks: {
title: function(tooltipItems, data) {
var idx = tooltipItems[0].index;
return 'Title:' + data.labels[idx];//do something with title
},
label: function(tooltipItems, data) {
//var idx = tooltipItems.index;
//return data.labels[idx] + ' ';
return tooltipItems.xLabel + ' ';
}
}
},
}
回答by Quince
So the way i went about this was to add a new option called labelLength
which, if passed a number greater than 0, will trim the labels on the x axis to that length.
所以我解决这个问题的方法是添加一个名为的新选项labelLength
,如果传递的数字大于 0,则会将 x 轴上的标签修剪为该长度。
It happens in the scale class of the chart and will only apply to the axis label and not the tool tip.
它发生在图表的比例类中,仅适用于轴标签而不适用于工具提示。
If you wanted you could extract the relevant bits and just override the scale class and also the build scale function in the bar chart to include the new option.
如果您愿意,您可以提取相关位,只需覆盖条形图中的比例类和构建比例函数以包含新选项。
In the scale class here is what was added
在比例类中,这是添加的内容
Chart.Scale = Chart.Element.extend({
initialize: function() {
//truncate the labels if option is grater than 0
this.xLabels = this.labelLength > 0 ? this.xLabels.map(this.truncateLabel, this) : this.xLabels;
this.fit();
},
truncateLabel: function(label) {
return label.substring(0, this.labelLength);
},
addXLabel: function(label) {
//also added here for when adding single items of data to a graph
this.xLabels.push(this.labelLength > 0 ? this.truncateLabel(label) : label);
this.valuesCount++;
this.fit();
},
}
}
then in the bar buildscale
function you would need to pass the option to the scale.
然后在 barbuildscale
函数中,您需要将选项传递给比例。
Or i have included this in my fork of chart js (https://github.com/leighquince/Chart.js) to use just pass the option labelLength
with your desired labels length, example below
或者我已经将它包含在我的图表 js ( https://github.com/leighquince/Chart.js) 的分支中,以使用仅传递labelLength
具有所需标签长度的选项,示例如下
var randomScalingFactor = function() {
return Math.round(Math.random() * 100)
};
var barChartData = {
labels: ["January a really long label", "February a really long label", "March a really long label", "April a really long label", "May a really long label", "June a really long label", "July a really long label"],
datasets: [{
fillColor: "rgba(220,220,220,0.5)",
strokeColor: "rgba(220,220,220,0.8)",
highlightFill: "rgba(220,220,220,0.75)",
highlightStroke: "rgba(220,220,220,1)",
data: [randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor()]
}, {
fillColor: "rgba(151,187,205,0.5)",
strokeColor: "rgba(151,187,205,0.8)",
highlightFill: "rgba(151,187,205,0.75)",
highlightStroke: "rgba(151,187,205,1)",
data: [randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor()]
}, {
fillColor: "rgba(15,18,20,0.5)",
strokeColor: "rgba(15,18,20,0.8)",
highlightFill: "rgba(15,18,20,0.75)",
highlightStroke: "rgba(15,18,20,1)",
data: [randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor()]
}]
}
window.onload = function() {
var ctx = document.getElementById("canvas").getContext("2d");
window.myBar = new Chart(ctx).Bar(barChartData, {
labelLength: 10,
});
}
<script src="http://www.quincewebdesign.com/cdn/Chart.js"></script>
<div style="width: 50%">
<canvas id="canvas" height="450" width="600"></canvas>
</div>
回答by Dustin Maxey
Just some additional info (can't comment, but thought this would be helpful) I added a small bit of code to the answer above to get "..." to show if labels are truncated.
只是一些附加信息(无法发表评论,但认为这会有所帮助)我在上面的答案中添加了一小段代码以获取“...”以显示标签是否被截断。
truncateLabel: function(label) {
var xSubstring = label.substring(0, this.labelLength);
if(xSubstring.length < this.labelLength) {
return xSubstring;
} else {
// Check if a word is cut off
if ( ' ' != label.charAt( (this.labelLength-1) ) && ' ' != label.charAt( this.labelLength ) ) {
// If so, cut the label off at the last space instead of mid-word
var last_space_pos = label.lastIndexOf(" ", this.labelLength);
last_space_pos = (0 > last_space_pos)? this.labelLength: last_space_pos;
xSubstring = label.substring(0, last_space_pos);
}
return xSubstring+"...";
}
},
回答by Terminal
This can be achieved without modifying the plugin code with customTooltips:function(tooltip)
option documented here.
A sample code is also provided hereto modifying tooltips for line graph. Using that snippet its fairly easy to achieve the desired behavior.
- Create a div for custom tooltip.
- Truncate the labels for x-axis but keep the mapping to original text in an array.
- In customTooltip function, populate tooltip div with original text by using tooltip.text
as key in mapping array.
这可以在不使用此处customTooltips:function(tooltip)
记录的选项修改插件代码的情况下实现。此处还提供了一个示例代码来修改折线图的工具提示。使用该片段很容易实现所需的行为。
- 为自定义工具提示创建一个 div。
- 截断 x 轴的标签,但将与原始文本的映射保留在数组中。
- 在 customTooltip 函数中,通过使用作为映射数组中的键,用原始文本填充工具提示 div 。tooltip.text