在chart.js中为每个标签设置特定颜色 [英] Setting specific color per label in chart.js

查看:160
本文介绍了在chart.js中为每个标签设置特定颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为使用 chart.js 库制作的图表设置颜色。

I'm trying to set colors for charts made using chart.js library.

我需要为每个数据标签使用特定的颜色。但是当特定标签的数据为零时,颜色会变得混乱:(..

I need a specific color for each data label. but when data of specific labels is zero colors get confused :(.

好像该库删除了零数据标签,并且标签的颜色也有所不同。

it looks like the library drops zero-data labels and labels colored differently.

例如,当数据为:


  • 颜色: 绿色红色黄色

  • 标签: 通过失败进行中

  • 数据: 0 5 80

  • colors: green, red, yellow,
  • labels: passed, failed, in progress
  • data: 0, 5, 80

通过的标记数据将被跳过,因为其值为零,所以失败的标记数据将获得第一种颜色:绿色,依此类推。

passed labeled data will be skipped as its value is zero, so failed labeled data gets the first color: green, and so on.

如何强制颜色匹配?

当前代码:

html:

<canvas baseChart height="150px" width="150px" [data]="graphData" [labels]="graphLabels" [colors]="graphColors"
    [options]="graphOptions" [legend]="false" [chartType]="'doughnut'">
</canvas>

TypeScript:

TypeScript:

this.graphData = this.data.map(r => r.cnt);
this.graphLabels = this.data.map(r => r.city);
this.graphOptions = {
    layout: {padding: 20},
    cutoutPrecentage: 90,
    legend: {display: false}
};

谢谢!

推荐答案

var graphData = {
    labels: ['Passed', 'Failed', 'In Progress'],
    datasets: [{
        label: 'Data',
        data: [0, 5, 80],
        backgroundColor: [
            "green",
            "red",
            "yellow"
        ],
    }]
};

或者在图表创建中添加数据

Or in your chart creation add the data


仅当您执行新图表(...)

graphData 作为 canvas 的参数很好



var chr = new Chart(ctx, {
    data: graphData,
    type: 'pie',
    options: options,
});

jsFiddle

这篇关于在chart.js中为每个标签设置特定颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆