Mohammad A. Souri
Mohammad A. Souri

Reputation: 177

How to limit xAxes and yAxes in React Chart JS?

I'm trying to make the below graph using chart js in React 18:

enter image description here

So far I've written the below code and tried to limit the x and y axes through maxTicksLimit, but I suppose I'm missing something here:

import "./styles.css";
import { data } from "./data";
import { Line } from "react-chartjs-2";
import moment from "moment";

export default function App() {
  const series = data.cpu.values.map((item) => item[1]);
  const labels = data.cpu.values.map((item) =>
    moment(item[0] * 1000).format("hh:mm:ss")
  );

  const options = {
    responsive: true
  };

  const datax = {
    labels,
    datasets: [
      {
        label: "CPU USAGE",
        data: series,
        borderColor: "rgb(255, 99, 132)",
        backgroundColor: "rgba(255, 99, 132, 0.5)",
        pointRadius: 0,
        fill: true
      }
    ],
    scales: {
      xAxes: [
        {
          ticks: {
            maxTicksLimit: 9
          }
        }
      ],
      yAxes: [
        {
          ticks: {
            maxTicksLimit: 4
          }
        }
      ]
    }
  };

  return (
    <div className="App">
      <Line options={options} data={datax} />
    </div>
  );
}

I get the below output:

enter image description here

I would appreciate any help CodeSandBox

Upvotes: 0

Views: 785

Answers (1)

uminder
uminder

Reputation: 26190

To solve your problem, define options as follows.

const options = {
  responsive: true,
  scales: {
    x: {
      ticks: {
        maxTicksLimit: 9
      }
    },
    y: {
      ticks: {
        maxTicksLimit: 4
      }
    }
  }
};

For further information, consult Tick Configuration Options from the Chart.js documentation.

Please take a look at your amended CodeSandbox and see how it works.

Upvotes: 1

Related Questions