Chartjs-Chartjs-plugin: How to add a different color to each label?

0👍

you need to provide backgroundColor: [] in Pie Chart for background color. Here is the complete example:

import React from "react";
import {makeStyles} from "@material-ui/core/styles";
import {Pie} from "react-chartjs-2";

const useStyles = makeStyles(theme => ({
    chart: {
        marginLeft: theme.spacing(2)
    }
}));

export default function PieChartExample(props) {
    const classes = useStyles();
    const [data, setdata] = React.useState({
        labels: ["type1", "type2", "type3", "type4"],
        datasets: [
            {
                label: "No. of registrations made",
                backgroundColor: [
                    "#3e95cd",
                    "#8e5ea2",
                    "#3cba9f",
                    "#e8c3b9",
                    "#c45850"
                ],
                barThickness: 80,
                data: [50, 100, 75, 20, 0]
            }
        ]
    });

    const getChartData = canvas => {
        return data;
    };
    return (
        <React.Fragment>
            <div
                className={classes.chart}
                style={{position: "relative", width: 900, height: 450}}
            >
                <Pie
                    options={{
                        responsive: true,
                        maintainAspectRatio: true,
                        legend: {display: true},
                        title: {
                            display: true,
                            text: "Title for the graph"
                        }
                    }}
                    onElementsClick={(e) => { console.log(e, 'e')}}
                    data={getChartData}
                />
            </div>
        </React.Fragment>
    );
}

Leave a comment