Javascript 格式化 Highcharts y 轴标签
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26127212/
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
Format Highcharts y-axis labels
提问by Dónal
I'm using Highcharts to generate a line chart that shows currency values. By default the y-axis labels use metric prefixes for abbreviation, e.g. 3k is displayed instead of 3000
我正在使用 Highcharts 生成显示货币价值的折线图。默认情况下,y 轴标签使用公制前缀作为缩写,例如显示 3k 而不是 3000
I would like to prepend a currency symbol to these labels, e.g. display $3k instead of 3k. However as soon as I add the currency symbol, the metric prefixes are no longer used. I've tried the following
我想在这些标签前添加一个货币符号,例如显示 $3k 而不是 3k。但是,一旦我添加了货币符号,就不再使用公制前缀。我试过以下
yAxis: {
labels: {
formatter: function () {
return '$' + this.value;
}
}
}
and also tried
也试过了
yAxis: {
labels: {
format: '${value}'
}
}
But in both cases $3000 is displayed instead of $3k. Is it possible to add a currency symbol without losing the metric prefix?
但在这两种情况下,都会显示 3000 美元而不是 3000 美元。是否可以在不丢失公制前缀的情况下添加货币符号?
Here's a demo (JSFiddle here) that illustrates the problem
这是说明问题的演示(此处为 JSFiddle)
$(function() {
$('#container').highcharts({
yAxis: {
// if you include the lines below, the metric prefixes disappear
/*
labels: {
format: '${value}'
}
*/
},
series: [{
data: [15000, 20000, 30000]
}]
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<div id="container" style="height: 400px; width: 500px"></div>
回答by Barbara Laird
You can call the original formatter from your formatter function:
您可以从格式化程序函数中调用原始格式化程序:
$(function () {
$('#container').highcharts({
yAxis: {
labels: {
formatter: function () {
return '$' + this.axis.defaultLabelFormatter.call(this);
}
}
},
series: [{
data: [15000, 20000, 30000]
}]
});
});
回答by Dmitry
I looked in HighCharts source code and found out that if you pass a formator formatterit won't add numeric symbol. It is inside else ifstatement i.e. formatOption xor numericSymbol. So you need to add a formatter and do the logic yourself.
我查看了 HighCharts 源代码,发现如果传递 aformat或formatter它不会添加数字符号。它在else if语句内部,即 formatOption xor numericSymbol。所以你需要添加一个格式化程序并自己做逻辑。
this is a slightly modified copy-paste of their code:
这是他们代码的稍微修改的复制粘贴:
formatter: function() {
var ret,
numericSymbols = ['k', 'M', 'G', 'T', 'P', 'E'],
i = numericSymbols.length;
if(this.value >=1000) {
while (i-- && ret === undefined) {
multi = Math.pow(1000, i + 1);
if (this.value >= multi && numericSymbols[i] !== null) {
ret = (this.value / multi) + numericSymbols[i];
}
}
}
return '$' + (ret ? ret : this.value);
}

