問題描述
避免 Google 圖表中 X 軸的小數點 (Avoid decimal points in X‑axis in Google charts)
我正在使用 Google 圖表,並創建了一個水平堆疊圖表。我繪製圖表的數組是
[['name','count',{ role: "style" }],
['abc', 1, '#4CAF50'],
['pqr', 2, '#4CAF50'],
['xyz', 1, '#4CAF50'],
['efg', 1, '#4CAF50'],
['klm', 2, '#4CAF50']]
這導致 X 軸
點 0.5, 1.0, 1.5, 2.0.
但是我想避免X軸上的小數點。
為此我嘗試了:
hAxis: {
format: '#'
}
AND
hAxis: {
format: '0'
}
但是這些給出 X 軸
為:1, 1, 2, 2。
這是不可取的。
I想要 X 軸
點類似於:1,2,3,4
我該怎麼做?任何幫助都是非常可觀的......
參考解法
方法 1:
You could specify X‑axis explicitly via ticks
option. But since your goal is set ticks based on the input data, you could specify it as demonstrated below:
google.load("visualization", "1", { packages: ["corechart"] });
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Year', 'Sold Books (M)', { role: 'annotation' }],
['2010', 1.1, ''],
['2011', 3.0, ''],
['2012', 9.0, ''],
['2013', 7.3, ''],
['2014', 3.5, '']
]);
var options = {
width: 600,
height: 400,
legend: { position: "none" },
isStacked: true,
hAxis: {
ticks: calcIntTicks(data,1)
}
};
var chart = new google.visualization.BarChart(document.getElementById("barchart_values"));
chart.draw(data, options);
}
function calcIntTicks(dataTable,step) {
var min = Math.floor(dataTable.getColumnRange(1).min);
var max = Math.ceil(dataTable.getColumnRange(1).max);
var vals = [];
for (var cur = min; cur <= max; cur+=step) {
vals.push(cur);
}
return vals;
}
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<div id="barchart_values" style="width: 900px; height: 300px;"></div>
方法 2:
Try the ticks option. Here is the fiddle for it.
ticks: [1, 2, 3]
(by Deepu Sasidharan、Vadim Gremyachev、Raman)