2011-10-08 154 views
1

有誰知道我可以如何重新格式化我的軸谷歌圖表?格式谷歌圖表軸

目前我在我的v軸上列出字節,但它顯示字節,我希望它顯示KB,因爲有時價值高達數十萬。

我試過閱讀配置選項(特別是vAxis.format),但它似乎並不支持我想要做的事情。我可以用這種方式格式化我的V軸嗎?還是我只能用字節來顯示它?

+0

難道你不能只提供KB而不是字節的值? – NullUserException

+0

我可以,但是我仍然有將KB轉換成MB的問題。我只是不知道是否有標準的格式化選項可以進行轉換。 – hohner

回答

1

退房this小提琴我放在一起。

google.setOnLoadCallback(drawStuff); 

function drawStuff() { 

    var data = new google.visualization.arrayToDataTable([ 
     ['Move', 'Percentage'], 
     ["King's pawn (e4)", 4400000000], 
     ["Queen's pawn (d4)", 3100000000], 
     ["Knight to King 3 (Nf3)", 1200000000], 
     ["Queen's bishop pawn (c4)", 200000000], 
     ['Other', 100000000] 
    ]); 

    var ranges = data.getColumnRange(1); 

    var log1024 = Math.log(1024); 

    var scaleSuffix = [ 
     "B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"]; 

    function byteFormatter(options) {} 

    byteFormatter.prototype.formatValue = function (value) { 
     var scale = Math.floor(Math.log(value)/log1024); 
     var suffix = scaleSuffix[scale]; 
     var scaledValue = value/Math.pow(1024, scale); 
     return Math.round(scaledValue * 100)/100 + " " + suffix; 
    }; 

    byteFormatter.prototype.format = function (dt, c) { 
     var rows = dt.getNumberOfRows(); 
     for (var r = 0; r < rows; ++r) { 
      var v = dt.getValue(r, c); 
      var fv = this.formatValue(v); 
      dt.setFormattedValue(r, c, fv); 
     } 
    }; 

    var formatter = new byteFormatter(); 

    formatter.format(data, 1); 

    var max = ranges.max * 1; 

    var options = { 
     title: 'Chess opening moves', 
     width: 900, 
     legend: { 
      position: 'none' 
     }, 
     chart: { 
      subtitle: 'popularity by percentage' 
     }, 
     allowHtml: true, 
     vAxis: { 
      ticks: [{ 
       v: 0 
      }, { 
       v: max * 0.2, 
       f: formatter.formatValue(max * 0.2) 
      }, { 
       v: max * 0.4, 
       f: formatter.formatValue(max * 0.4) 
      }, { 
       v: max * 0.6, 
       f: formatter.formatValue(max * 0.6) 
      }, { 
       v: max * 0.8, 
       f: formatter.formatValue(max * 0.8) 
      }, { 
       v: max, 
       f: formatter.formatValue(max) 
      }] 
     }, 
     axes: { 
      x: { 
       0: { 
        side: 'top', 
        label: 'White to move' 
       } // Top x-axis. 
      }, 
     }, 
     bar: { 
      groupWidth: "90%" 
     } 
    }; 

    var chart = new google.visualization.ColumnChart(document.getElementById('top_x_div')); 
    // Convert the Classic options to Material options. 
    chart.draw(data, options); 
}; 

如果在繪製圖表後不動態更改數據,此解決方案可以很好地工作。如果數據隨後發生變化(例如使用Control),則此解決方案不允許垂直軸的自動縮放。 如果底層數據發生更改,則應在重新調用draw之前重新計算max值,以正確縮放垂直軸。

我知道這是一個老問題,你可能已經移動了... 我找不到任何其他人做類似的事情,並遇到了同樣的情況。

+0

@Amedeo感謝您抓住這個難題。我忘了這一切。 – TylerY86