React chartjs-2 - 增加图例和图表之间的间距
React chartjs-2 - Increase spacing between legend and chart
我正在使用 react chartjs 2
。我需要增加图例和图表之间的边距。在这里,我发现了很多不适用于 react 或 nextjs 的解决方案。这就是为什么我需要用反应环境来解决它。请帮助我。
这是我的代码-
import { Box, Typography } from "@mui/material";
import { Line } from 'react-chartjs-2';
import {
Chart as ChartJS,
CategoryScale,
LinearScale,
PointElement,
LineElement,
Title,
Tooltip,
Legend
} from 'chart.js';
ChartJS.register(
CategoryScale,
LinearScale,
PointElement,
LineElement,
Title,
Tooltip,
Legend
);
const options = {
responsive: true,
plugins: {
legend: {
labels: {
boxHeight: 2,
boxWidth: 50
},
},
}
};
const data = {
labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
datasets: [
{
id: 1,
label: 'iPhone',
data: [65, 59, 80, 81, 56, 55, 40],
}
]
};
const DownloadChart = () => {
return (
<Box>
<Typography variant="h5" component="h5">
Device Download
</Typography>
<Line
datasetIdKey='id'
data={data}
options={options}
/>
</Box>
);
};
export default DownloadChart;
我看到有可用的 beforeInit 和 afterInit 函数。但我不知道我该如何应用它。请帮助我。
您可以使用自定义插件:
ChartJS.register({
id: 'customSpacingLegend',
beforeInit(chart) {
// Get reference to the 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)();
// Change the height as suggested in another answers
this.height += 15;
}
};
});
我正在使用 react chartjs 2
。我需要增加图例和图表之间的边距。在这里,我发现了很多不适用于 react 或 nextjs 的解决方案。这就是为什么我需要用反应环境来解决它。请帮助我。
这是我的代码-
import { Box, Typography } from "@mui/material";
import { Line } from 'react-chartjs-2';
import {
Chart as ChartJS,
CategoryScale,
LinearScale,
PointElement,
LineElement,
Title,
Tooltip,
Legend
} from 'chart.js';
ChartJS.register(
CategoryScale,
LinearScale,
PointElement,
LineElement,
Title,
Tooltip,
Legend
);
const options = {
responsive: true,
plugins: {
legend: {
labels: {
boxHeight: 2,
boxWidth: 50
},
},
}
};
const data = {
labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
datasets: [
{
id: 1,
label: 'iPhone',
data: [65, 59, 80, 81, 56, 55, 40],
}
]
};
const DownloadChart = () => {
return (
<Box>
<Typography variant="h5" component="h5">
Device Download
</Typography>
<Line
datasetIdKey='id'
data={data}
options={options}
/>
</Box>
);
};
export default DownloadChart;
我看到有可用的 beforeInit 和 afterInit 函数。但我不知道我该如何应用它。请帮助我。
您可以使用自定义插件:
ChartJS.register({
id: 'customSpacingLegend',
beforeInit(chart) {
// Get reference to the 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)();
// Change the height as suggested in another answers
this.height += 15;
}
};
});