1
votes

I need to display two independent series on a Google Chart. The series represent temperature and pressure within the same given timeframe, however, the sampling times may be different. Below an sample of my data

let temperatures = [["Apr 26, 2019, 4:28:28 AM", 25.509],
                    ["Apr 26, 2019, 4:28:38 AM", 26.509],
                    ["Apr 26, 2019, 4:28:48 AM", 25.590],
                    ["Apr 26, 2019, 4:28:58 AM", 25.515],
                    ["Apr 26, 2019, 4:29:08 AM", 24.998]]

let pressures =     [["Apr 26, 2019, 4:28:30 AM", 60.509],
                     ["Apr 26, 2019, 4:28:41 AM", 60.509],
                     ["Apr 26, 2019, 4:28:50 AM", 60.590] 
                     ["Apr 26, 2019, 4:28:57 AM", 60.998]]

Is there a way to draw a chart with such data?

From my understanding, both ScatterChart and ComboChart expect the same x-axis value.

1

1 Answers

0
votes

the charts just expect the x-axis value to be in the same / first column.
but we can use null where the series doesn't have a value for the x-axis value.

we can use google's join method to combine the two data sets.

var dataTemp = google.visualization.arrayToDataTable(temperatures, true);
var dataPres = google.visualization.arrayToDataTable(pressures, true);
var dataChart = google.visualization.data.join(dataTemp, dataPres, 'full', [[0, 0]], [1], [1]);

and the following options to place the pressures on a second y-axis.

var options = {
  series: {
    1: {
      targetAxisIndex: 1,
    }
  }
};

see following working snippet...

google.charts.load('current', {
  packages:['corechart']
}).then(function () {
  let temperatures = [
    ["Apr 26, 2019, 4:28:28 AM", 25.509],
    ["Apr 26, 2019, 4:28:38 AM", 26.509],
    ["Apr 26, 2019, 4:28:48 AM", 25.590],
    ["Apr 26, 2019, 4:28:58 AM", 25.515],
    ["Apr 26, 2019, 4:29:08 AM", 24.998]
  ];

  let pressures = [
    ["Apr 26, 2019, 4:28:30 AM", 60.509],
    ["Apr 26, 2019, 4:28:41 AM", 60.509],
    ["Apr 26, 2019, 4:28:50 AM", 60.590],
    ["Apr 26, 2019, 4:28:57 AM", 60.998]
  ];

  var dataTemp = google.visualization.arrayToDataTable(temperatures, true);
  var dataPres = google.visualization.arrayToDataTable(pressures, true);
  var dataChart = google.visualization.data.join(dataTemp, dataPres, 'full', [[0, 0]], [1], [1]);
  dataChart.setColumnLabel(1, 'Temperature');
  dataChart.setColumnLabel(2, 'Pressure');

  var options = {
    chartArea: {
      height: '100%',
      width: '100%',
      top: 24,
      left: 60,
      right: 16,
      bottom: 100
    },
    height: 400,
    width: '100%',
    series: {
      1: {
        targetAxisIndex: 1,
      }
    }
  };

  var chart = new google.visualization.ScatterChart(document.getElementById('chart_div'));
  chart.draw(dataChart, options);
});
<script src='https://www.gstatic.com/charts/loader.js'></script>
<div id='chart_div'></div>