【问题标题】:Chartjs-plugin: How to add a different color to each label?Chartjs-plugin:如何为每个标签添加不同的颜色?
【发布时间】:2020-09-17 04:02:45
【问题描述】:

我有一个用 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】:

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

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

    【讨论】:

    • 感谢您的帮助,但恐怕这不是我想要的。我说的是改变每个馅饼内标签的颜色。在每个饼图内显示标签只能通过 chartjs-plugin 实现。我已经有一个格式正确的数据集。
    • 我刚刚在您写评论时更新了我的示例。我不确定你是否检查了我的更新。你能检查一下并告诉我吗?
    • 我已经在沙箱中运行了您的示例,这不是我要寻找的 :(。我说的是每个馅饼中的标签。我用图片编辑了我的原始帖子所以我的要求更清楚了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-03
    • 2020-06-19
    • 1970-01-01
    • 2014-10-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多