Chartjs-plugin:如何为每个标签添加不同的颜色?

问题描述 投票:0回答:1

我有一个用chartjs制作的饼图。然后,借助chart-js插件,我在每个饼图上添加了标签。有时,馅饼背景有点浅,所以我的白色文字不够清晰。在这种情况下,我已经创建了一个功能来检查对比度并将其着色为黑色。

但是当应用于chartjs-plugin的标签颜色属性时,该函数仅运行一次,并且对所有标签保持相同的颜色。如何根据标签的背景将不同的颜色应用于每个标签?

这里是代码:

 plugins: {
                datalabels: {
                  color: function(ctx: any) {
                    [...Array(ctx.dataset.data.length)].map((_, i) => {
                      return transformColor(ctx.dataset.backgroundColor[i]);
                    });
                  },

谢谢!

javascript reactjs chart.js
1个回答
0
投票

您需要在backgroundColor: []图表中提供Pie作为背景色。这是完整的示例:

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: false},
                        title: {
                            display: true,
                            text: "Title for the graph"
                        }
                    }}
                    onElementsClick={(e) => { console.log(e, 'e')}}
                    data={getChartData}
                />
            </div>
        </React.Fragment>
    );
}
© www.soinside.com 2019 - 2024. All rights reserved.