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

5
  • Can we see your code?
    – Natu Myers
    May 26, 2017 at 20:08
  • of course, I'll add it. May 26, 2017 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, 2017 at 2: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 May 31, 2017 at 8:43
  • I have same question: stackoverflow.com/questions/46551434/…. Did you find a way to do it? Oct 17, 2017 at 21:04

1 Answer 1

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
        }
      }]
    }
  }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.