在Google折线图上左右切换X和Y轴

时间:2019-05-30 14:04:27

标签: charts google-visualization

在我的X轴上是ip地址(字符串),在Y轴上是百分比(数字),但是我想切换它们,当我尝试在我的代码上执行时,得到“给定的所有序列轴必须具有相同的数据类型”错误。我认为这是因为不允许第一列为数字。

切换addColumn / addRow语句以数字(内存使用率和CPU使用率)开头,以服务器IP结尾。 使用arrayToDataTable代替DataTable。

           /*<![CDATA[*/
            var serverStatuses = /*[[${serverStatuses}]]*/ 'default';
            /*]]>*/
            var performanceData =new google.visualization.DataTable();

            performanceData.addColumn('number', 'CPU Usage');
            performanceData.addColumn('number', 'Memory Usage');
            performanceData.addColumn('string', 'Server IP');

            for (var n = 0; n < serverStatuses.length; n++) {
                performanceData.addRow([serverStatuses[n].memoryUsage,
                    serverStatuses[n].cpuUsage, 
                 serverStatuses[n].ipAddress]);
            }

Y轴上的IP地址和X轴上的百分比。

1 个答案:

答案 0 :(得分:0)

as you've discovered, you cannot have a string on the y-axis of a line chart.
see the data format for specifics...

however, we can use object notation to represent the ip address by a number.
then display the address instead of the number.

when loading a cell in google's data table,
we can provide an intrinsic value, such as --> '127.0.0.1'

or we can use an object, and provide both the value (v:) and the formatted value (f:)
{v: 0, f: '127.0.0.1'}

this will cause the chart to use zero for the value, but display the address on the chart.
this solves half of our problem, by loading the data in the data table.

now we must solve the issue of the labels actually displayed on the y-axis.
here, we can use the ticks option.
the ticks option will accept the same object notation above.
so if we want ip addresses on the y-axis, supply ticks as follows...

[{v: 0, f: '127.0.0.1'}, {v: 0.1, f: '127.0.0.2'}, {v: 0.2, f: '127.0.0.3'}]

see following working snippet for an example...

google.charts.load('current', {
  packages: ['corechart']
}).then(function () {
  var serverStatuses = [
    {memoryUsage: 0.1, ipAddress: '127.0.0.1'},
    {memoryUsage: 0.3, ipAddress: '127.0.0.2'},
    {memoryUsage: 0.5, ipAddress: '127.0.0.3'},
    {memoryUsage: 0.7, ipAddress: '127.0.0.4'},
    {memoryUsage: 0.9, ipAddress: '127.0.0.5'},
  ];

  var performanceData = new google.visualization.DataTable();
  performanceData.addColumn('number', 'Memory Usage');
  performanceData.addColumn('number', 'Server IP');

  var axisTicks = [];
  serverStatuses.forEach(function (row, index) {
    var address = {
      v: index,
      f: row.ipAddress
    };
    axisTicks.push(address);
    performanceData.addRow([
      row.memoryUsage,
      address
    ]);
  });

  var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
  chart.draw(performanceData, {
    vAxis: {
      ticks: axisTicks
    }
  });
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>