Chart.js two Y-axes, one with negative values

I have two Y axes in my line chart. One of the charts can show negative values ​​from -1 to 1 (left axis). The other has values ​​from 0 to X (right axis). The problem is that the left point has 0 points in the middle, the right axis shows 0 at the bottom.

Is there any fix? Some thing how to set a negative maximum value as the minimum value for the right axis will solve it. But I don't know how to do it.

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 mainly use this solution: qaru.site/questions/295776 / ...

+3


source to share


1 answer


If the left graph is always -1

1

, you need the right graph from -z

to z

.

Given your dataset, compute the maximum value (if your correct set included negative numbers, you would also need the smallest number, then take the absolute value for both and see which is larger, but your code says it is only positive).

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



Adjust your parameters this way

  options: {
    scales: {
      yAxes: [{
        id: 'left',
        type: 'linear',
        position: 'left',
      }, {
        id: 'right',
        type: 'linear',
        position: 'right'
        ticks: {
          min: -yMax,
          max: yMax
        }
      }]
    }
  }

      

0


source







All Articles