reactjsreact-hookschart.jsreact-chartjs-2

How do we change the position of legend in chart.js-2 react


i am trying to move the legends from top to bottom but not able to move the position Since i am learning charts and trying to implement it to react need some help

also i need to change the size of the doughnut chart(should be small/thin) and need to add c text at center

 import React from "react";
 import { Chart as ChartJS, ArcElement, Tooltip, Legend } from "chart.js";
 import { Doughnut } from "react-chartjs-2";

 ChartJS.register(ArcElement, Tooltip, Legend);

 export const data = {
 labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
 datasets: [
 {
  label: "# of Votes",
  data: [12, 19, 3, 5, 2, 3],
  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,
  Legend: {
    display: true,
    position: "bottom",
  },
  },
  ],
  };

  export function App() {
  return <Doughnut data={data} />;
  }

I tried adding postions={legend:{position:"bottom"}}

also

const options = {
  legend: {
    labels: {
      padding: 20
    }
  }
};

Solution

  • Assuming you're using Chart.js version 4.n, legend options need to be defined inside options.plugins.legend. The legend can be moved to the bottom of the chart through the position option as follows:

    const options = {
      plugins: {
        legend: {
          labels: {
            position: 'bottom'
          }
        }
      }
    };