React-chartjs-2:如何在图表和图例之间添加空间?



我试图在实际图表和图例/标签之间添加一个空间。
图例有一个正确的位置,我不知道如何在图表和标签之间添加padding/margin。
发现一些讨论,但不相关的反应挂钩。
根据我的理解,我需要利用beforeinit内置的功能。

下面是代码片段和沙箱链接。

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

任何帮助都将不胜感激

您不能添加空间,但使用beforeInit插件(codesandbox)增加图例的宽度。增加宽度会增加一些空间,但会减少图表可用的整体宽度,所以你可能需要稍微调整一下-

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

相关内容

  • 没有找到相关文章

最新更新