首页 > 解决方案 > Chart JS 中体积数据集的规模较小

问题描述

我正在绘制一些股票数据,我想将交易量放在底部较小的灰色条数据集中,就像在雅虎财经中一样。

我想要的是:

小的灰色数据集位于底部。

我想要的截图

我得到什么:

三个不同的 Y 尺度和体积数据集的大小是相同的。

我得到的截图

我的代码:

当我创建图表时:

new Chart(context, {
    type: 'line',
    data: {
      labels: timestamps.map(n => 
        (new Date(n * 1000)).toLocaleString()
      ),
      datasets: [
        dataset,
        vdataset
      ]
    },
    options: {
      maintainAspectRatio: false,
      scales: {
        xAxis: {
          // type: 'time'
          ticks: {
            //autoSkip: true,
            maxTicksLimit: 10
          }
        },
        yAxes: [{
          id: 'volume',
          display: false
        }],
        y: {
          beginAtZero: false
        },
      },
      animation: {
        duration: 0
      },
      plugins: {
        autocolors: false,
        annotation: {
          annotations
        }
      },
      tooltips: {
        mode: 'nearest'
      },
      hover: {
        intersect: false
      }
    }
  });

体积数据集:

{
    type: 'bar',
    label: `Volume`,
    data: ...,
    backgroundColor: 'transparent',
    borderColor: 'grey',
    fill: 'origin',
    pointRadius: 0,
    borderWidth: 2,
    yAxisID: 'volume'
  }

标签: javascriptdatasetchart.jsscale

解决方案


你需要给每个数据集一个yAxisID,然后你应该用这个 id 命名你的轴,如下所示:

数据:

var data = {
  labels: labels,
  datasets: [{
    label: 'My First Dataset',
    data: generateTestSeries(),
    fill: false,
    borderColor: 'rgb(75, 192, 192)',
    tension: 0.1,
    yAxisID: "something",
  },
  {
    label: 'My Second Dataset',
    data: generateTestSeries(),
    fill: false,
    borderColor: 'rgb(182, 50, 192)',
    tension: 0.1,
    yAxisID: "volume",
  },
  ]
};

秤:

scales: {
    volume: {
        axis: "y",  
        min: -80,
        max: 60,
        position: 'right',
    },
    something: {
        axis: "y",
        min: -20,
        max: 70,
        position: 'left',
    }
}

此外,您不应该有列表 yAxes,这就是在 chartjs 2.x 中定义轴的方式

这是一个使用中的小提琴:JSFiddle

编辑:如果您想要一个不可见的轴,只需设置displayfalse现在更新的小提琴中所见。


推荐阅读