格式化Google折线图的x轴

时间:2017-04-24 19:58:35

标签: javascript html google-visualization

我有一个谷歌折线图,我提供了一些数据,如下例所示:

['Time', 'Temperature'],
['00:00', 5, ],
['01:00', 12, ],
['02:00', 14, ],
['03:00', 18, ],
['04:00', 17, ],
['04:20', 17, ],
['04:30', 18, ],
['04:40', 22, ],
['05:00', 24, ],
['06:00', 20, ],
['07:00', 17, ],
['08:00', 17, ],
['09:00', 16, ],
['10:00', 17, ],
['11:00', 16, ],
['12:00', 15, ]

我希望x轴在24小时模式下只显示一天中的小时数。

每小时可以有一个或多个值,但x轴的范围应该是固定的和线性的(0-23)。

看看小提琴:https://jsfiddle.net/1b3hd0ya/10/

怎么办呢?

修改

实际上,可以通过在x轴上使用正确的Date对象并使用HH:mm格式化它们来解决问题。

1 个答案:

答案 0 :(得分:0)

它会像这样工作,这意味着我必须更改日期格式。

https://jsfiddle.net/1b3hd0ya/12/

  google.charts.load('current', {
      'packages': ['line', 'corechart']
  });
  google.charts.setOnLoadCallback(drawVisualization);

  function drawVisualization() {
      var data = google.visualization.arrayToDataTable([
          ['Time', 'Temperature'],
          [new Date(2017, 0, 1, 0, 0, 0), 5],
          [new Date(2017, 0, 1, 1, 0, 0), 12],
          [new Date(2017, 0, 1, 2, 0, 0), 14],
          [new Date(2017, 0, 1, 3, 0, 0), 18],
          [new Date(2017, 0, 1, 4, 0, 0), 17],
          [new Date(2017, 0, 1, 4, 20, 0), 17],
          [new Date(2017, 0, 1, 4, 30, 0), 18],
          [new Date(2017, 0, 1, 4, 40, 0), 22],
          [new Date(2017, 0, 1, 5, 0, 0), 24],
          [new Date(2017, 0, 1, 6, 0, 0), 20],
          [new Date(2017, 0, 1, 7, 0, 0), 17],
          [new Date(2017, 0, 1, 8, 0, 0), 17],
          [new Date(2017, 0, 1, 9, 0, 0), 16],
          [new Date(2017, 0, 1, 10, 0, 0), 17],
          [new Date(2017, 0, 1, 11, 0, 0), 16],
          [new Date(2017, 0, 1, 12, 0, 0), 15]
      ]);

      new google.visualization.LineChart(document.getElementById('visualization')).
      draw(data, {
          "height": 500,
          "curveType": "function",
          "lineWidth": 2,
          "pointSize": 2,
          "vAxes": {
              "0": {
                  "title": "°C",
                  "format": "#,##00.00 °C"
              }
          },
          "hAxes": {
              "0": {
                  "title": "Time",
                  "format": 'HH:mm'
              }
          },
          "series": {
              "0": {
                  "targetAxisIndex": 0
              }
          }
      });
  };