4

I've got two Y-axis in my line chart. One of the charts can show negative values between -1 and 1 (left axis). The other one has values from 0 to X (right axis). Problem is, that the left has the 0 point in the middle, the right axis shows 0 at the bottom.

Is there any fix to it? Some thing like set the negative max value as min value for the right axis would solve it. But I don't know how to perform this.

var ctx = document.getElementById('myChart');
var myChart = new Chart(ctx, {
  type: 'line',
  data: {
    labels: dates,
    datasets: [{
      label: 'Sentiment',
      yAxisID: 'left',
      data: normalizedSentiment // contains from -1 to 1
    }, {
      label: 'Count',
      yAxisID: 'right',
      data: count // only positive
    }]
  },
  options: {
    scales: {
      yAxes: [{
        id: 'left',
        type: 'linear',
        position: 'left',
      }, {
        id: 'right',
        type: 'linear',
        position: 'right'
      }]
    }
  }
});

I basically used this solution: https://stackoverflow.com/a/38094165/1193235

seniorbenelli
  • 838
  • 1
  • 9
  • 20
  • Can we see your code? – Natu Myers May 26 '17 at 20:08
  • of course, I'll add it. – seniorbenelli May 26 '17 at 21:12
  • I'm not exactly clear on what you are trying to do. Do you want the zero's to line up in the middle? Do you want to use the same scale on both sides? Can you add a sketch of what you want the final graph to look like? – Tot Zam May 29 '17 at 02:19
  • I want to have both zero lines in the middle, so that they are aligned. The Scale on both side mustn't be the same, only important is, that zero is on both sides at the same place – seniorbenelli May 31 '17 at 08:43
  • I have same question: https://stackoverflow.com/questions/46551434/chart-js-with-dual-axis-incorrect-starting-points-if-negative-values. Did you find a way to do it? – Ulad Melekh Oct 17 '17 at 21:04

1 Answers1

0

If the left chart is always -1 to 1, then you need the right chart to be from -z to z.

Given your dataset, calculate the max value (if your right set included negative numbers you'd also need the least number, then take the absolute value of both and see which is greater, but your code says it's only positive).

Something like const yMax = Math.max(...dataset.map(d => d.y));

Set your options up like this

  options: {
    scales: {
      yAxes: [{
        id: 'left',
        type: 'linear',
        position: 'left',
      }, {
        id: 'right',
        type: 'linear',
        position: 'right'
        ticks: {
          min: -yMax,
          max: yMax
        }
      }]
    }
  }
claudekennilol
  • 992
  • 2
  • 13
  • 26