Chartjs-How do we put one time series on the left Y-axis and another on the right Y-axis?

0👍

You can achieve this by providing yAxisID in each datasets data. Following that, mentioning position of each y axis in options.scales.

In the below code, I have made two y axis yAxis: y and yAxis: y1 and mentioned the position left for axis y and position right for axis y1.

You can read more about multi axis line chart here – link

const ctx = document.getElementById("chart").getContext("2d");

var xValues = [8.8, 8.6, 9.0, 9.7, 9.5, 9.1, 9.0, 9.2, 9.0, 9.6];
var yValues = [31.0, 23.0, 23.0, 45.29, 44.21, 3.53, 83.0, 21.0, 80.0, 38.88]
var labels = ['W12', 'W13', 'W14', 'W15', 'W16', 'W17', 'W18', 'W1P', 'W2P', 'W3P'];

const chart6 = new Chart(ctx, {
  type: "line",
  data: {
    labels: labels,
    datasets: [{
      data: xValues,
      borderColor: "green",
      fill: false,
      label: "Salary",
      yAxisID: 'y',
    }, {
      data: yValues,
      borderColor: "orange",
      fill: false,
      label: "Ownership",
      yAxisID: 'y1',
    }],
  },
  options: {
    legend: {
      display: true
    },
    title: {
      display: true,
      text: "Salary & Ownership"
    },
    scales: {
      y: {
        type: "linear",
        display: true,
        position: "left",
      },
      y1: {
        type: "linear",
        display: true,
        position: "right",
      },
    },
  }
});
#container {
  width: clamp(250px, 80%, 1024px);
  margin-inline: auto;
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
  row-gap: 2em;
}

#chart {
  position: relative;
  max-width: 400px;
  max-height: 300px;
}
<body>
  <div id="container">
    <canvas id="chart" width="400" height="300" role="img" area-label="First Chart for showing frequencies with year." tabindex="0">
  </div>
<!--  Date Adaptor (Moment) CDN -->
  <script src="https://cdn.jsdelivr.net/npm/chart.js@^3"></script>
  <script src="https://cdn.jsdelivr.net/npm/moment@^2"></script>
  <script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-moment@^1"></script>
  
<!--  Chart.js CDN  -->
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.8.0/chart.min.js">    
  </script>
</body>

Leave a comment