reactjschart.jsreact-chartjs

How to remove X and Y axis with react-chartjs-2


I cannot find a solution to this anywhere and it is driving me crazy. I have a line chart using the react-chartjs-2 package. This is how my code looks:

const CHARTDATA = {
    labels: dates,
    datasets: [
      {
        backgroundColor: dates[0]! > dates[dates.length - 1]! ? "red" : "green",
        borderColor: dates[0]! > dates[dates.length - 1]! ? "red" : "green",
        data: prices,
      },
    ],
  };

  const CHARTOPTIONS = {
    responsive: true,
    plugins: {
      legend: {
        display: false,
        
      },
     
    },
  };

  return <Line data={CHARTDATA} options={CHARTOPTIONS} />;

All of this works fine, but I have no clue on how to customize the axes (y and x). All I'm trying to do is remove both the axes titles so there is no text on the left hand side (y axes) or bottom (x axes). I'm guessing it's somewhere within the CHARTOPTIONS but not too sure. I have found so many conflicting answers online and I honestly think this package has horrible documentation. Does anyone know how to customize the axes?


Solution

  • In React-chartjs-2 if you want to hide the axis label you'll have to configure the chartOptions.

    Here's how you can hide the label, sure you can play around with a lot of other options by checking the examples.

    React-chartjs-2 examples

    const CHARTOPTIONS = {
      responsive: true,
      plugins: {
        legend: {
          display: false,
        },
      },
    
      // Modify the axis by adding scales
      scales: {
        // to remove the labels
        x: {
          ticks: {
            display: false,
          },
    
          // to remove the x-axis grid
          grid: {
            drawBorder: false,
            display: false,
          },
        },
        // to remove the y-axis labels
        y: {
          ticks: {
            display: false,
            beginAtZero: true,
          },
          // to remove the y-axis grid
          grid: {
            drawBorder: false,
            display: false,
          },
        },
      },
    };