Javascript 如何在图表 API x/y 轴标签中仅显示整数(无小数)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7124659/
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
How to show only integers (no decimals) in chart API x/y-axis labels
提问by jpswain
I'm using a column chart with the Google Chart JS Api. I'm displaying some values (total orders by day) that can only be represented as integers.
我正在使用带有 Google Chart JS Api 的柱形图。我正在显示一些只能表示为整数的值(按天计算的总订单)。
Everything is working great, except that when one of the charts I'm displaying has values that are too low, like 1 or 2, it starts to show decimals on the y-axis. The decimals look silly b/c it's impossible to have "half" an order (which is what I'm counting), and I'd like to hide this if possible.
一切都很好,除了当我显示的其中一个图表的值太低(如 1 或 2)时,它开始在 y 轴上显示小数。小数看起来很傻 b/c 不可能有“一半”的订单(这是我正在计算的),如果可能的话,我想隐藏它。
回答by BigBadMe
I don't have enough rep to reply to Ian Hunter's post directly, but what that does is format the label, but doesn't set the grid lines to the same value as the label, which can have undesirable results. So let's say you have these grid lines:
我没有足够的代表直接回复 Ian Hunter 的帖子,但这样做是格式化标签,但不会将网格线设置为与标签相同的值,这可能会产生不良结果。假设您有这些网格线:
10
10
7.5
7.5
5
5
2.5
2.5
0
0
When you format the label to only show integers it shows this: 10 8 5 3 0
当您将标签格式化为仅显示整数时,它会显示:10 8 5 3 0
But then your data on the graph doesn't tie-in with the y-scale labels. E.g If you have a value of 3 it actually shows abovethe '3' labels because the '3' label is actually 2.5
但是,您在图表上的数据不会与 y 尺度标签相关联。例如,如果您的值为 3,它实际上显示在 '3' 标签上方,因为 '3' 标签实际上是 2.5
Unfortunately, the only solution I could think of was to monitor the min/max ranges of the data shown in the graph, and then apply some logic to set the min/max according to how many y-scale labels I have, such that they would divide with no remainders.
不幸的是,我能想到的唯一解决方案是监视图中显示的数据的最小/最大范围,然后根据我拥有的 y 尺度标签的数量应用一些逻辑来设置最小/最大值,这样它们将除以没有余数。
So in the case above, I'd set it to
所以在上面的例子中,我将它设置为
vAxis: {
viewWindow:{
max:12,
min:0
}
}
This would give grid lines of
这会给网格线
12
12
8
8
6
6
4
4
0
0
No decimals, and no problems with the data not correlating with the labels on the graph.
没有小数,并且数据与图表上的标签不相关也没有问题。
回答by Thaer Mohazia
use the option
使用选项
vAxis: {format: '0'}
as in
如
chart.draw(data, {
width: 800,
height: 480,
orientation: 'horizontal',
vAxis: {format: '0'}
}
);
回答by prad
Adding {format : 0} converts the float ticks to integers but the actual values on the bars appear incorrectly.
添加 {format : 0} 会将浮动刻度转换为整数,但条形图上的实际值显示不正确。
The main issue is Google Charts API assumes you want 5 gridlines mostly which may not work out to give you integer tick values.
主要问题是 Google Charts API 假设您主要需要 5 条网格线,这些网格线可能无法为您提供整数刻度值。
Adding this gave me nice round tick values -
添加这个给了我很好的圆形刻度值 -
gridlines: { count: -1}
source - https://groups.google.com/forum/#!topic/google-visualization-api/4qCeUgE-OmU
来源 - https://groups.google.com/forum/#!topic/google-visualization-api/4qCeUgE-OmU
回答by Yevgeniy Afanasyev
if you want only the integer values to be shown, you should take to account that google charts wants to show you at least 5 gridlines. Presuming all of them should be integer give the graph following:
如果你只想显示整数值,你应该考虑到谷歌图表想要显示至少 5 条网格线。假设所有这些都应该是整数,请给出以下图表:
vAxis: { title: 'Orders Count',
minValue: 4,
viewWindow:{min:0}, /*this also makes 0 = min value*/
format: '0',
},
回答by Bernie
The easiest way is to edit the left vertical axis, with Min as 0, and Max as a multiple of 5 (5, 10, 15 etc) as appropriate to your expected maximum.
最简单的方法是编辑左边的垂直轴,将最小值设为 0,最大值设为 5 的倍数(5、10、15 等),视您的预期最大值而定。
回答by Muhammad Shaban
This issue will be resolved if you use vAxis: {gridlines: { count: 4}}
如果您使用,此问题将得到解决 vAxis: {gridlines: { count: 4}}
回答by Cagy79
In my case I have values ranging from 0 to 600.
就我而言,我的值范围从 0 到 600。
- if $value is smaller than 12: use the max value for vAxis.gridlines.count
- if $value is greater than 12: use the default nr of gridlines (4)
- 如果 $value 小于 12:使用 vAxis.gridlines.count 的最大值
- 如果 $value 大于 12:使用网格线的默认 nr (4)
In this way you only display 'whole numbers'.
通过这种方式,您只能显示“整数”。
You'll need to dynamically generate the javascript off course.
您需要在课程之外动态生成 javascript。
Code Example:
代码示例:
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Fase', 'Closed', 'Open'],
<?php
$max = 0; // needed to determine the number of gridlines?
$data = array();
foreach($projectExecutions as $key => $pe){
$totals = countOpenIssuesInProjectExecution($pe);
$open = $totals['open'];
$closed = $totals['closed'];
$data[] = "['". $FASE[$pe['fase_id']] . "', " . $closed . ", ". $open . "]\r\n";
// What are the Max values vor Open & Closed Defects
if($open > $max ){ $max = $open; }
if($closed > $max ){ $max = $closed; }
}
$nrOfGridLines = ($max >= 12 ? 4 : $max+1); // Calculate the number of gridlines
echo implode(",",$data);
?>
]);
var options = {
legend: { position: 'bottom' }
,title: "Evolution Defects: Open -VS- Closed"
,colors:['#00a160','red']
,isStacked: true
,vAxis: {textPosition: 'in', minValue:0,viewWindow: { min: 0 }, gridlines: {count: <?php echo $nrOfGridLines; ?>} }
};
var chart = new google.visualization.AreaChart(document.getElementById('chart_defects'));
chart.draw(data, options);
}
回答by Vitali D.
I'm using the following code:
我正在使用以下代码:
google.charts.setOnLoadCallback(function(){
var data = new google.visualization.DataTable();
data.addColumn('string', 'Y');
data.addColumn('number', 'X');
var max = 0; //Or something like Int.MinValue
for (var i = 0;i< arr.length;i++) {
max = (arr[i]>max)? arr[i]:max; //calculate max value
data.addRow("<<some calculation>>");
}
var options = {
height: 300,
vAxis: {
gridlines: { count: max+1}, //+1 is importent for the origingridline
viewWindow:{
min: 0,
max: max
},
}
};
var chart = new google.visualization.ColumnChart(document.getElementById("<< div_id >>"));
chart.draw(data, options);
}
Just calculate your maximum value and then set gridlines.count to this value
只需计算您的最大值,然后将 gridlines.count 设置为该值
回答by Gregory Alan Bolcer
I'm using the Guava Multiset as my data. Cagy79's trick is the only one that I was able to get working. I also tried generating my own lines using an IntStream, but still had fractional numbers for some of the graphs. As mentioned above, just setting the format will create a graph where the hover over value and the gridline differ.
我使用 Guava Multiset 作为我的数据。Cagy79 的技巧是我唯一能够开始工作的技巧。我也尝试使用 IntStream 生成我自己的线条,但仍然有一些图形的小数。如上所述,仅设置格式将创建一个图形,其中悬停值和网格线不同。
Multiset items = TreeMultiset.create();
Multiset items = TreeMultiset.create();
Items added using .add and .addAll
使用 .add 和 .addAll 添加的项目
Make sure the items are sorted:
确保项目已排序:
occurrences = Multisets.copyHighestCountFirst(items);
出现次数 = Multisets.copyHighestCountFirst(items);
String option = "hAxis : { title : 'Count', gridlines : { count:" + ((max >=12) ? 4 : max+1) + } }")
String option = "hAxis : { title : 'Count', gridlines : { count:" + ((max >=12) ? 4 : max+1) + } }")
回答by Simon_Weaver
I prefer the gridlines: { count: -1 }
option, but you can always explicitly specify the values you want with ticks
. Cool thing about this is they don't even have to be evenly spaced - you could do [1, 10, 100, 200, 500, 1000] if you wanted:
我更喜欢该gridlines: { count: -1 }
选项,但您始终可以使用ticks
. 很酷的一点是它们甚至不必均匀间隔 - 如果您愿意,您可以执行 [1, 10, 100, 200, 500, 1000] :
options: { vAxis: { ticks: [1,2,3,4,5,6,7,8,9,10] } }
options: { vAxis: { ticks: [1,2,3,4,5,6,7,8,9,10] } }
Depending upon your data you may want to hardcode this or use thresholds.
根据您的数据,您可能希望对此进行硬编码或使用阈值。