2
votes

I'm trying to plot multiple y-axis in chartjs using a horizontalBar chart.

Here's what the final graph should look like:

enter image description here

Here's my chart config:

{
  type: 'horizontalBar',
  data: {
    labels: ['a', 'b', 'c', 'd', 'e'],
    datasets: [{
      label: 'A',
      yAxisID: 'A',
      data: [10, 20, 30, 40, 50],
      backgroundColor: 'blue'
    }, {
      label: 'B',
      yAxisID: 'B',
      data: [10, 20, 30, 40, 50],
      backgroundColor: 'red'
    }]
  },
  options: {
    scales: {
      xAxes: [{
        ticks: {
          beginAtZero: true
        }
      }],
      yAxes: [{
        id: 'A',
        position: 'left'
      }, {
        id: 'B',
        position: 'right'
      }]
    }
  }

The first dataset (the blue one) shows up correctly and with the correct y-axis values (ie. a, b, c, etc.)

But the second dataset does not appear at all. Also, the y-axis for the second dataset (right side), shows 50, 40, 30, etc. instead of a, b, c...

PS: It is mandatory to show both the y-axes. This is because I have to plot the positive values (blue ones) against the y-axis on the right side, and the negative values (red ones) against the y-axis on the left side.

Here's the jsFiddle

1
@ℊααnd Thanks, but that's not what I exactly want, because there is still single y-axis on the left. I have to show tick labels on the right side (using the second y-axis), for all the positive (blue) values - Anubhav Dhawan
@ℊααnd I've added an image of what I finally expect - Anubhav Dhawan

1 Answers

1
votes

Change your second 'data' object's 'label' and 'yAxisID' values from 'B' to 'A'. Also, you can delete your second 'yAxes' object at the bottom.

So it would look like this:

var canvas = document.getElementById('chart');
new Chart(canvas, {
  type: 'horizontalBar',
  data: {
    labels: ['a', 'b', 'c', 'd', 'e'],
    datasets: [{
      label: 'A',
      yAxisID: 'A',
      data: [100, 90, 80, 70, 60],
      backgroundColor: 'blue'
    }, {
      label: 'A',
      yAxisID: 'A',
      data: [-100, -90, -80, -70, -60],
      backgroundColor: 'red'
    }]
  },
  options: {
    scales: {
      yAxes: [{
        id: 'A',
        position: 'left'
      }]
    }
  }
});

jsfiddle: https://jsfiddle.net/vjt2r1mL/362/