[Chartjs]-Relative bar chart overlay on line chart in chart.js

1👍

use a second y-axis to give the bar series a different scale

assign each data set to its own axis by using property –> yAxisID

then set the matching id of the y-axis in the scales.yAxes option

see following working snippet…

$(document).ready(function() {
  let marketData = [["Nov 28 2018 20: +0",30.332,"103"],["Nov 28 2018 21: +0",25.801,"188"],["Nov 28 2018 22: +0",25.451,"262"],["Nov 28 2018 23: +0",12.484,"693"]];

  let lineData = [];
  let barData = [];
  let labels = [];

  marketData.forEach(function(thing) {
    labels.push(thing[0].replace(' +0', '00'));
    lineData.push(thing[1]);
    barData.push(thing[2]);
  });

  new Chart(document.getElementById("mixed-chart"), {
    type: 'bar',
    data: {
      labels: labels,
      datasets: [
        {
          label: "Price",
          type: "line",
          borderColor: "#3e95cd",
          data: lineData,
          fill: false,
          yAxisID: 'A'  // <-- set y-axis id
        },
        {
          label: "Sold",
          type: "bar",
          backgroundColor: "rgba(0,0,0,0.2)",
          data: barData,
          yAxisID: 'B'  // <-- set y-axis id
        }
      ]
    },
    options: {
      title: {
        display: true,
        text: 'Sale price vs sale volume'
      },
      legend: {display: false},
      scales: {
        yAxes: [{
          id: 'A',  // <-- set y-axis id
          position: 'left',
        }, {
          id: 'B',  // <-- set y-axis id
          position: 'right',
          
          // hide grid lines and labels
          gridLines: {
            display: false
          },
          ticks: {
            display: false
          }
        }]
      }
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.bundle.min.js"></script>
<canvas id="mixed-chart"></canvas>

Leave a comment