Search code examples
reactjsreact-chartjs-2

Making fixed y-Axis scales with react-chartjs-2


i want to create a chart with Chart.js and React that has a persistant yAxis ranging form -15 to 15 with a stepSize of 5. As an example i copied the dynamic Bar Chart that can be found here: https://reactchartjs.github.io/react-chartjs-2/#/dynamic-bar

the documentation of charjs.org mentions min and max properties of the Axis here: https://www.chartjs.org/docs/3.2.0/samples/scales/linear-min-max.html but react-chartjs-2 seems to ignore these values. I tried:

  1. Old Naming: scales.yAxis
  2. New Naming: scales.y
  3. adding "scaleOverride : true" to options.scales and option.scales.y
  4. inside the "ticks"
  5. outside the "ticks"
  6. Removing everything in the config.scales.y but min, max and stepsize with old and new naming

My current App.js:

import React, { useEffect, useState } from 'react';
import { Bar } from 'react-chartjs-2';

const rand = () => Math.round(Math.random() * 20 - 10);

const genData = () => ({
  labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
  datasets: [
    {
      label: 'Scale',
      data: [rand(), rand(), rand(), rand(), rand(), rand()],
      backgroundColor: [
        'rgba(255, 99, 132, 0.2)',
        'rgba(54, 162, 235, 0.2)',
        'rgba(255, 206, 86, 0.2)',
        'rgba(75, 192, 192, 0.2)',
        'rgba(153, 102, 255, 0.2)',
        'rgba(255, 159, 64, 0.2)',
      ],
      borderColor: [
        'rgba(255, 99, 132, 1)',
        'rgba(54, 162, 235, 1)',
        'rgba(255, 206, 86, 1)',
        'rgba(75, 192, 192, 1)',
        'rgba(153, 102, 255, 1)',
        'rgba(255, 159, 64, 1)',
      ],
      borderWidth: 1,
    },
  ],
});

const options = {
  scales: {
    scaleOverride : true,
    y: [
      {
        type: "time",
        ticks: {
          min: 0,
          max: 150,
          stepSize: 20
        },
        
      },
    ],
    x: [
      {
        type: "Amp",
        ticks: {
        },
        
      },
    ],
  },
};

function App() {
  const [data, setData] = useState(genData());

  useEffect(() => {
    const interval = setInterval(() => setData(genData()), 1000);
    return () => clearInterval(interval);
  }, []);

  return (
    <>
      <Bar className="Linechart" data={data} options={options} />
    </>
  );
};

export default App;


Can someone please explain to me what is the correct way to set the y-Axis to a fixed range? Thanks in advance.


Solution

  • It was a simple syntax error. Using this config works:

    const options = {
      scales: {
        y:
          {
            min: -15,
            max: 15,
            stepSize: 5,
          },
        x:
          {
            
          },
      },
    };