Kyle
Kyle

Reputation: 30

How can I create a bar chart that has multiple yAxes scales?

I have the following code:

data = {
    labels: ["CategoryA", "CategoryB"],
    datasets: [
        {
           label: "Group A",
           data: [95, 1]
        },
        {
           label: "Group B",
           data: [80, 3]
        }
    ]
};

new Chart(ctx, {
        type: 'bar',
        data: data, 
        options: option
});

My goal is to directly compare the numbers in Group A and Group B per category. However, the bars for CategoryA take up the entire vertical space while CategoryB is barely visible.

How can I make CategoryA display on a scale from 0 to 100 and CategoryB on a scale from 0 to 5?

EDIT: Here was the problem I had. Was unable to make a solution with only one graph, ended up just using two separate ones. If anyone knows how to do it in one graph, please let me know!

Upvotes: 0

Views: 845

Answers (1)

ɢʀᴜɴᴛ
ɢʀᴜɴᴛ

Reputation: 32869

Unfortunately, there is no built-in method in ChartJS to achieve this at the moment.

Though, one way I can think of achieving this, is to create two different charts and place them on top of each other, as such ...

// CHART 1
var data = {
   labels: ["Category A", "Category B", "Category C"],
   datasets: [{
      label: "Group A",
      data: [95, 0, 0],
      backgroundColor: 'blue'
   }, {
      label: "Group B",
      data: [60, 0, 0],
      backgroundColor: 'red'
   }]
};
var option = {
   scales: {
      yAxes: [{
         ticks: {
            min: 0,
            max: 100
         }
      }]
   }
}
new Chart(ctx, {
   type: 'bar',
   data: data,
   options: option
});

// CHART 2
var data2 = {
   labels: ["Category A", "Category B", "Category C"],
   datasets: [{
      label: "Group A",
      data: [0, 1, 2],
      backgroundColor: 'blue'
   }, {
      label: "Group B",
      data: [0, 3, 4],
      backgroundColor: 'red'
   }]
};
var option2 = {
   scales: {
      yAxes: [{
      	position: 'right',
         ticks: {
            min: 0,
            max: 5
         }
      }]
   }
}
new Chart(ctx2, {
   type: 'bar',
   data: data2,
   options: option2
});
#chart-wrapper {
   display: flex;
}
#ctx2 {
   position: absolute;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<div id="chart-wrapper">
   <canvas id="ctx"></canvas>
   <canvas id="ctx2"></canvas>
</div>

Upvotes: 1

Related Questions