Chartjs with multiple y axes and different scales

Chartjs with multiple y axes and different scales

by Aline Matos

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.bundle.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/numeral.js/2.0.6/numeral.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/numeral.js/2.0.6/locales/pt-br.min.js"></script>
<html>
  <body>
    <div class="myChartDiv">
      <canvas id="myChart" width="600" height="400"></canvas>
    </div>
  </body>
</html>

JavaScript

var dataSet = {
  labels: ['Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho',
           'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro'],
  datasets: [{
    type: 'bar',
    label: 'Total Mensal',
    id: 'y-axis-0',
    backgroundColor: '#17522f',
    borderColor: '#17522f',
    borderWidth: 2,
    data: [ 1450478,2645844,1840524,640057,1145844,1530500,1695844,1778654,1450478,1645844,1450478,1645844
          ]
  }, {
    type: 'line',
    label: 'Preço Médio Mensal',
    id: 'y-axis-1',
    borderColor: '#2c9659',
    backgroundColor: '#2c9659',
    borderWidth: 2,
    data: [
      3.14, 4.15, 3.09, 3.48, 4.05, 3.99, 4.39, 4.15, 4.10, 3.98, 3.54, 3.50
    ]
  }]
};

var chart = new Chart(document.getElementById('myChart'), {
  type: 'bar',
  data: dataSet,
  options: {
    title: {
      display: false
    },
    tooltips: {
      mode: 'label'
    },
    responsive: true,
    scales: {
      xAxes: [{
        stacked: true
      }],
      yAxes: [{
        stacked: true,
        position: 'left',
        type: 'linear',
        scaleLabel: {
          display: true,
        },
        id: 'y-axis-0',
        ticks: {
          beginAtZero:true,
          callback: function (tick, index, ticks) {
            return numeral(tick).format('(0,0)');
          }
        }
      }, {
        stacked: false,
        position: 'right',
        type: 'linear',
        id: 'y-axis-1',
        ticks: {
          max: 10,
          stepSize: 1,
          display: true,
          beginAtZero: true,
          fontColor: '#17522f',
          fontSize: 13,
          padding: 10,
          callback: function (tick, index, ticks) {
            return numeral(tick).format('$0,0.00');
          }
        }
      }]
    }
  }
});