Multiple baselines with dual y-axis Google Chart

2019-04-02 05:26发布

问题:

I'm using the Google Visualization API for a simple sales chart that has two series, number of sales and sales value, that I'm showing on a column chart with two vetical axes. The sales value can be negative, such as for returns, but this is causing the graph to show two different baselines. The zero baseline for number of sales is in line with the lowest sales value figure. Here's an example of the code with some sample data:

google.load('visualization', '1.0', { 'packages': ['corechart'] });
google.setOnLoadCallback(drawSalesChart);

function drawSalesChart() {
    var dataTable = new google.visualization.DataTable();
    dataTable.addColumn('string', 'Order Source');
    dataTable.addColumn('number', 'Num Sales');
    dataTable.addColumn('number', 'Sales Value');

    dataTable.addRows([
        ['Web (Order)', 300, 31000],
        ['Call Centre (Order)', 700, 61000],
        ['Call Centre (Return)', 50, -4100],
        ['Call Centre (Exchange)', 10, 800]
    ]);

    var options = {
        title: 'Sales by Order Source',
        hAxis: { title: 'Order Source' },
        series: {
            0: { targetAxisIndex: 0 },
            1: { targetAxisIndex: 1 },
        },
        vAxes: {
            0: { title: 'Num Sales' },
            1: { title: 'Sales Value' }
        }
    };

    new google.visualization.ColumnChart(
        document.getElementById('livesales-chart-container')).draw(dataTable, options);
}

I've been through the API documentation as there's information on setting the baseline but there doesn't seem to be a way to tie the zero of each vAxis to the same point. I've tried searching Google and StackOverflow and there are similar questions but I can't see that anyone has had this problem.

How can I, or even can I, show a single baseline at zero for both series?

回答1:

From a visualization perspective, it may be a lot better to create two separate charts on top of each other since the data provided is very different both in scope and in what it is explaining.

<!--
You are free to copy and use this sample in accordance with the terms of the
Apache license (http://www.apache.org/licenses/LICENSE-2.0.html)
-->

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <title>
      Google Visualization API Sample
    </title>
    <script type="text/javascript" src="http://www.google.com/jsapi"></script>
    <script type="text/javascript">
      google.load('visualization', '1', {packages: ['corechart']});
    </script>
    <script type="text/javascript">

      function drawSalesChart() {
        var dataTable = new google.visualization.DataTable();
        dataTable.addColumn('string', 'Order Source');
        dataTable.addColumn('number', 'Num Sales');
        dataTable.addColumn('number', 'Sales Value');

        dataTable.addRows([
          ['Web (Order)', 300, 31000],
          ['Call Centre (Order)', 700, 61000],
          ['Call Centre (Return)', 50, -4100],
          ['Call Centre (Exchange)', 10, 800]
        ]);

        var dataView1 = new google.visualization.DataView(dataTable);
        dataView1.setColumns([0,1]);

        var dataView2 = new google.visualization.DataView(dataTable);
        dataView2.setColumns([0,2]);

        var options1 = {
          title: 'Sales by Order Source',
          hAxis: { title: 'Order Source' },
          vAxis: { title: 'Num Sales' }
        };

        var options2 = {
          title: null,
          hAxis: { title: null, textPosition: 'none' },
          vAxis: { title: 'Sales Value' }
        };

        new google.visualization.ColumnChart(
          document.getElementById('chart1')).draw(dataView1, options1);
        new google.visualization.ColumnChart(
          document.getElementById('chart2')).draw(dataView2, options2);
      }

      google.setOnLoadCallback(drawSalesChart);

    </script>
  </head>
  <body style="font-family: Arial;border: 0 none;">
    <div id="chart1" style="width: 600px; height: 300px;"></div>
    <div id="chart2" style="width: 600px; height: 100px;"></div>
  </body>
</html>

Of course, this would need some prettying-up to make the graphs line up properly, and to make the colors work as you'd like, but this way you can focus on the main data you want to show, while keeping the other info nearby as a reference.

If you are insistent on doing them on the same graph, you will need to write a function to be able to calculate where the grid lines should lie (or figure out how Google does it, but I couldn't find it on a web search).

To figure out what the max/min values should be on a graph, an "easy" way is to take the difference between the minimum and maximum values, count the number of grid lines you will have (default for google is 5), round up to the nearest significant digit of your biggest number, and use those as your grid line dividers.

e.g. Taking your first column: 300, 700, 50, 10

Max Value: 700
Min Value: 10
Exponent: LEN(Max)-1 = 2 = 10^2, nearest 100
Grid Lines: 5 - 1 = 4 (assuming you want the bottom value to serve as the floor at the same rounding, you need 4 more iterations to go over the top value)
Difference Between Max and Min: 690
Required Interval: 690 / 4 = 172.5
Rounded up to the nearest 100: 200

Min Value: FLOOR(Min,200) = 0
Max Value: CEILING(Max,200) = 800

Grid Line 1: 0
Grid Line 2: 200
Grid Line 3: 400
Grid Line 4: 600
Grid Line 5: 800

Note, this matches what your chart shows. However, it won't work for negative values because the math gets a bit more complicated.

First you need to figure out the ratio of negative values to the total difference in min and max values.

e.g. Given your Column 2 data: 31000, 61000, -4100, 800

Min Value: -4100
Max Value: 61000
Difference: 65100
Negative Ratio: 6.3%

So 6.3% of your range is in the negative portion. Given 5 grid lines, that means that one grid line will need to be below 0, and you only have 4 grid lines for the positive portion. Since the negative portion is smaller than the positive portion, the positive portion will determine the grid line spacings.

So now you have 4 grid lines to cover the positive portion (0 - 61000), which means you have 3 segments from 0 to reach 61000.

That means 61000 / 3, rounded up to 4 significant digits, or 30,000.

That makes your gridlines:

-30,000
0
30,000
60,000
90,000

Coincidentally, this is what you got in your chart.

Now that you know the second series has 1 negative gridline, you'd have to readjust your first series to match the second one. So instead of having 5 gridlines (0 and 4 above), you now have 1 negative gridline, 1 0, and then 3 above zero that need to reach 700. So you take the 700 positive value you have, divide by 3, for 233.333.

Round that up to the nearest 100, and you get 300.

So your first chart max/min would be readjusted to -300, and 900 for the following gridlines:

-300
0
300
600
900

This will set the same baseline.

That will solve your problem -- all you need to do is code that logic in to Javascript! Let us know if you do it, I'm sure someone else will have the same issue down the line.