Chartjs-Chart.js – each dataset value = different axis

1πŸ‘

It is not possible to apply a different axis to a specific value in the dataset.

As I understand, you want

hehehe [KG] to scale with [kg] axis

You can solve this issue elegantly, by separating the dataset based on the units and then map each dataset to its required axis.


Code snippet

Chart.defaults.global.elements.line.fill = false;

var barChartData = {
  labels: ['2016', '2017', '2018', '2019'],
  datasets: [{
    type: 'bar',
    label: 'a',
    id: "y-axis-0",
    data: [1000, 2000, 4000, 5000],
    backgroundColor: "rgba(217,83,79,0.75)"
  }, {
    type: 'bar',
    label: 'b',
    id: "y-axis-0",
    data: [500, 600, 700, 800],
    backgroundColor: "rgba(92,184,92,0.75)"
  }, {
    type: 'line',
    label: 'c',
    id: "y-axis-0",
    data: [1500, 2600, 4700, 5800],
    backgroundColor: "rgba(51,51,51,0.5)"
  }, {
    type: 'line',
    label: 'd',
    id: "y-axis-1",
    data: [5000, 3000, 1000, 0],
    backgroundColor: "rgba(151,187,205,0.5)"
  }]
};

var element = document.getElementById("myChart");

// allocate and initialize a chart
var chart = new Chart(element, {
  type: 'bar',
  data: barChartData,
  options: {
    title: {
      display: true,
      text: "Chart.js Bar Chart - Stacked"
    },
    tooltips: {
      mode: 'label'
    },
    responsive: true,
    scales: {
      xAxes: [{
        stacked: true
      }],
      yAxes: [{
        stacked: true,
        position: "left",
        id: "y-axis-0",
      }, {
        stacked: false,
        position: "right",
        id: "y-axis-1",
      }]
    }
  }
});
.myChartDiv {
  max-width: 600px;
  max-height: 400px;
}
<!DOCTYPE html>
<html>

<head>
  <link href="style.css" rel="stylesheet">
  <script src="https://npmcdn.com/chart.js@2.7.2/dist/Chart.bundle.min.js">
  </script>
  </link>
</head>

<body>
  <div class="myChartDiv">
    <canvas height="400" id="myChart" width="600">
            </canvas>
  </div>
</body>
<script src="script.js">
</script>

</html>

Hope it helps!

Leave a comment