React-chartjs-2:如何在 Chart 和 Legend 之间添加 space?

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

我正在尝试在实际图表和 Legend/labels 之间添加一个 space。
图例有一个正确的位置,我不知道如何在图表和标签之间添加一个 padding/margin。
发现一些讨论但与 React Hooks 无关。
据我了解,我需要使用 beforeinit 内置函数。

这是代码片段和 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>
  );
}

任何帮助将不胜感激

您无法添加 space,但可以使用 beforeInit 插件 (codesandbox) 增加图例的宽度。增加宽度会增加一些 space 但它会减少图表可用的整体宽度,因此您可能需要稍微调整一下 -

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