Chartjs-Chart,js stepSize working for right hand Y axis but not left hand Y axis

0👍

You could try to force to use your ticks implementing axis callback:

afterBuildTicks(axis, ticks) {
  axis.ticks = [];
  for (let i = axis.options.ticks.min; i<=axis.options.ticks.max; i+=axis.options.ticks.stepSize) {
    axis.ticks.push(i);
  }
}
var dates = ['07/29/2022', '08/01/2022', '08/02/2022', '08/03/2022', '08/04/2022', '08/05/2022', '08/06/2022', '08/07/2022', '08/08/2022', '08/09/2022', '08/10/2022', '08/11/2022'];
var portfolio_values = [3869.73, 3802.77, 3811.14, 3813.0, 3818.58, 3954.36, 3954.36, 3954.36, 3993.42, 3983.19, 4131.99, 4086.42];
var sp500_values = [378.79, 377.65, 375.21, 381.07, 380.77, 379.98, 379.98, 379.98, 379.64, 378.14, 386.06, 386.43];

const ctx = document.getElementById("myChart");
const myChart = new Chart(ctx, {
          type: "line",
          data: {
            labels: dates,
            datasets: [{
                fill: false,
                lineTension: 0,
                backgroundColor: "rgba(0,0,255,1.0)",
                borderColor: "rgba(0,0,255,0.1)",
                yAxisID: "A",
                label: "Twitter",
                data: portfolio_values
              },
              {
                fill: false,
                lineTension: 0,
                backgroundColor: "rgba(255,0,0,1.0)",
                borderColor: "rgba(255,0,0,0.1)",
                yAxisID: "B",
                label: "S&P500",
                data: sp500_values
              }
            ]
          },
          options: {
            title: {
              display: true,
              text: "Twitter vs S&P500"
            },
            legend: {
              display: true
            },
            scales: {
              yAxes: [{
                  id: "A",
                  type: "linear",
                  position: "left",
                  ticks: {
                    min: 3800,
                    max: 4140,
                    stepSize: 34
                  }, 
                  afterBuildTicks(axis, ticks) {
                    axis.ticks = [];
                    for (let i = axis.options.ticks.min; i<=axis.options.ticks.max; i+=axis.options.ticks.stepSize) {
                      axis.ticks.push(i);
                    }
                  }
                },
                {
                  id: "B",
                  type: "linear",
                  position: "right",
                  ticks: {
                    min: 370,
                    max: 390,
                    stepSize: 2,
                  }
                }
              ]
            }
          }
        });  
.myChartDiv {
  max-width: 600px;
  max-height: 400px;
}
<script src="https://cdn.jsdelivr.net/npm/chart.js@2.9.4/dist/Chart.min.js"></script>
<html>
  <body>
    <div class="myChartDiv">
      <canvas id="myChart" width="600" height="400"/>
    </div>
  </body>
</html>

Leave a comment