Chart.js 的多轴折线图

Multi-axis line chart with Chart.js

以下代码我尝试在折线图上显示两个 y 轴,并在两个数据源中添加了 yAxisID。但是,它没有显示。我可以知道我的代码有什么问题吗?谢谢。

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();

在您代码的图表 options 中,yAxes 的定义过多(xAxis 前后)。

为了让它起作用,整个图表 options 基本上可以简化为您在下面看到的内容。

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.