Search code examples
javascriptdatasetchart.jsscale

Smaller scale for volume dataset in Chart JS


I'm graphing some stocks data and I wanted to put the volume in a smaller gray bar dataset at the bottom, like in Yahoo Finance.

What I want:

The small grey dataset is at the bottom.

screenshot of what I want

What I get:

Three different Y scales and the size of the volume dataset is the same a the other.

screenshot of what I get

My code:

When I create the chart:

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

The volume dataset:

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

Solution

  • you need to give every dataset a yAxisID and then you should name your axis with that id like this:

    Data:

    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:

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

    Also you shouldn't have the list yAxes, that was how axes were defined in chartjs 2.x

    Here is a fiddle to see this in use: JSFiddle

    edit: If you want an invisible axis just set display to false as seen in the now updated Fiddle.