Search code examples
react-hooksreact-chartjs-2

React-chartjs-2: How to add space between Chart and Legend?


I'm trying to add a space between the actual Chart and the Legend/labels.
Legend has a position rigtht and I don't know how to add a padding/margin between Chart and labels.
Found some discussions but not relevant to react hooks.
From what I understood, I need to make use of beforeinit built in function.

Here is the code snippet and sandbox link.

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

export function App() {
  return (
    <div style={{ width: "300px", height: "300px" }}>
      <Doughnut
        options={{
          maintainAspectRatio: true,
          plugins: {
            legend: {
              position: "right",
              rtl: true,
              labels: {
                usePointStyle: true,
                pointStyle: "circle",
                padding: 20
              }
            }
          }
        }}
        data={data}
      />
    </div>
  );
}

Any help will be appreciated


Solution

  • You can't add space but increase the width of the legend using the beforeInit plugin (codesandbox). Increasing the width adds some space but it decreases the overall width available to the chart, so you might have to tweak that a little -

    const plugin = {
      beforeInit(chart) {
        console.log("be");
        // reference of original fit function
        const originalFit = chart.legend.fit;
    
        // override the fit function
        chart.legend.fit = function fit() {
          // call original function and bind scope in order to use `this` correctly inside it
          originalFit.bind(chart.legend)();
          // increase the width to add more space
          this.width += 20;
        };
      }
    };
    
    <Doughnut
            plugins={[plugin]}
    ...