Search code examples
chart.jsreact-chartjs-2

React chartjs-2 - Increase spacing between legend and chart


I am using react chartjs 2. I need to increase margin between legend and chart. Here I found many solutions that are not for react or nextjs. That's why I need to solve it with react environment. Please help me.

Here is my code-

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;

I see that there are available beforeInit and afterInit function. But I am not knowing that How can I apply it. Please help me.


Solution

  • You can use a custom plugin:

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