如何防止Google图表更改x轴顺序?

时间:2017-01-02 18:06:04

标签: charts google-visualization

我试图绘制一个Google图表,其x轴代表周数。当我们越过新的一年时,轴转为50, 51, 52, 1, 2, 3, ...

我正确地订购了我的数据,但谷歌图表坚持要重新排序我的x轴,最后得到一个奇怪的图表:



var chartData = [
  ["Week","Revenue"],
  [40,227],
  [41,317],
  [42,320],
  [43,482],
  [44,418],
  [45,345],
  [46,313],
  [47,316],
  [48,380],
  [49,467],
  [50,349],
  [51,256],
  [52,393],
  [1,276],
  [2,349],
  [3,312]
];

google.load("visualization", "1", {
packages:["corechart"],
callback: function() {
  var div = document.getElementById('chart');
  var chartDataTable = google.visualization.arrayToDataTable(chartData);
  var chart = new google.visualization['LineChart'](div);
  chart.draw(chartDataTable);
}});

<div id="chart" style="height: 400px;">test</div>
<script src="//www.google.com/jsapi"></script>
&#13;
&#13;
&#13;

如何阻止它重新排序我的数据?

1 个答案:

答案 0 :(得分:1)

google的对象表示法允许您提供值(v:)和格式化值(f:

因此,您可以使用格式为1

'40'

e.g。 - &GT; {v: 1, f: '40'}

连续 - &gt; [{v: 1, f: '40'},227]

以下工作代码段使用对象表示法重新格式化x轴的值,
并重复使用x轴标签(hAxis.ticks

的值

&#13;
&#13;
var chartData = [
  ["Week","Revenue"],
  [40,227],
  [41,317],
  [42,320],
  [43,482],
  [44,418],
  [45,345],
  [46,313],
  [47,316],
  [48,380],
  [49,467],
  [50,349],
  [51,256],
  [52,393],
  [1,276],
  [2,349],
  [3,312]
];

var hAxisTicks = [];
chartData.forEach(function (row, index) {
  if (index === 0) {
    return;
  }
  row[0] = {
    v: index,
    f: row[0].toString()
  };
  hAxisTicks.push(row[0]);
});

google.charts.load('current', {
  callback: function () {
    var div = document.getElementById('chart');
    var chartDataTable = google.visualization.arrayToDataTable(chartData);
    var chart = new google.visualization['LineChart'](div);
    chart.draw(chartDataTable, {
      hAxis: {
        ticks: hAxisTicks
      }
    });
  },
  packages:['corechart']
});
&#13;
<div id="chart"></div>
<script src="https://www.gstatic.com/charts/loader.js"></script>
&#13;
&#13;
&#13;

注意:

建议使用loader.js加载库,而不是jsapi

根据release notes ...

  

通过jsapi加载程序保留的Google Charts版本不再一致更新。从现在开始请使用新的gstatic装载机。

这只会更改load语句,请参阅上面的代码段...

编辑:

连续轴有更多选项 必须按顺序排序,或按倒序排序('number''date'值)

但图表将遵循离散轴的原始排序顺序('string'值)

请参阅以下代码段'string'

discrete vs. continuous了解更多......

&#13;
&#13;
var chartData = [
  ["Week","Revenue"],
  [40,227],
  [41,317],
  [42,320],
  [43,482],
  [44,418],
  [45,345],
  [46,313],
  [47,316],
  [48,380],
  [49,467],
  [50,349],
  [51,256],
  [52,393],
  [1,276],
  [2,349],
  [3,312]
];

chartData.forEach(function (row, index) {
  if (index === 0) {
    return;
  }
  row[0] = row[0].toString();
});

google.charts.load('current', {
  callback: function () {
    var div = document.getElementById('chart');
    var chartDataTable = google.visualization.arrayToDataTable(chartData);
    var chart = new google.visualization['LineChart'](div);
    chart.draw(chartDataTable);
  },
  packages:['corechart']
});
&#13;
<div id="chart"></div>
<script src="https://www.gstatic.com/charts/loader.js"></script>
&#13;
&#13;
&#13;