Chart.js是两个Y轴,一个是负值

时间:2017-05-26 19:42:27

标签: javascript chart.js

我的折线图中有两个Y轴。其中一个图表可以显示-1和1之间的负值(左轴)。另一个具有从0到X(右轴)的值。问题是,左边的中间是0点,右边的轴是0。

有什么问题吗?将负最大值设置为右轴的最小值可以解决它。但我不知道如何执行此操作。

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'
      }]
    }
  }
});

我基本上使用了这个解决方案:https://stackoverflow.com/a/38094165/1193235

1 个答案:

答案 0 :(得分:0)

如果左侧图表始终从-11,则您需要右侧图表从-zz

给出您的数据集,计算出最大值(如果您的右集合包括负数,那么您也需要最少的数,然后取两者的绝对值,看看哪个更大,但您的代码说它只是正数)。

类似const yMax = Math.max(...dataset.map(d => d.y));

像这样设置您的选项

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