-1

The following code I tried to display two y-axis on the line chart and I added yAxisID in both the data source. However, it is nothing to shown. May I know what's wrong with my code? Thank you.

function BuildChart(labels, valuesa, valuesb, chartTitle) {
  var ctx = document.getElementById("myChart").getContext('2d');
  var myChart = new Chart(ctx, {
    type: 'line',
    data: {
      labels: labels,
      datasets: [{
        label: 'Temperature',
        fill: false,
        data: valuesa,
        yAxisID: 'y1',
        backgroundColor: 'red',
        borderColor: 'red',
      }, {
        label: 'Relative Humidity',
        fill: false,
        data: valuesb,
        yAxisID: 'y2',
        backgroundColor: 'blue',
        borderColor: 'blue',
      }]
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      scales: {
        y1: {
          type: 'linear',
          display: true,
          position: 'left',
          },
        y2: {
          type: 'linear',
          display: true,
          position: 'right',
        },
        xAxes: [{
          ticks: {
            beginAtZero: true,
            scaleLabel: {
              display: false,
              labelString: ''
            }
          }
        }],
        yAxes: [{
            scaleLabel: {
            display: false,
            labelString: '',
          }
        }]

      }
    }
  })
  return myChart;
};


var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
    var json = JSON.parse(this.response);

    // Map json labels  back to values array
    var labels = json.feed.entry.map(function(e) {
      return e.gsx$tag.$t;
    });

    // Map json values back to values array
    var valuesa = json.feed.entry.map(function(e) {
      return e.gsx$dailytemperature.$t
    });

    // Map json values back to values array
    var valuesb = json.feed.entry.map(function(e) {
      return e.gsx$dailyrh.$t
    });

    BuildChart(labels, valuesa, valuesb, "Temperature", "Relative Humidity");
  }
};
xhttp.open("GET", "https://spreadsheets.google.com/", false);
xhttp.send();
Dennis
  • 67
  • 1
  • 9

1 Answers1

1

Within the chart options of your code, there are too many definitions of yAxes (before and after xAxis).

To make it work, the entire chart options can basically be reduced to what you see below.

options: {
  responsive: true,
  maintainAspectRatio: false,
  scales: {
    yAxes: [{
        type: 'linear',
        position: 'left',
        id: 'y1',
      },
      {
        type: 'linear',
        position: 'right',
        gridLines: {
          drawOnChartArea: false
        },
        id: 'y2',
      }
    ]
  }
}

For further information, please consult Create Multiple Axis from the Chart.js documentation.

uminder
  • 23,831
  • 5
  • 37
  • 72