rk fred
rk fred

Reputation: 59

Setting specific color per label in 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.

For example, when data is:

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

How can I force colors matching?


Current code:

html:

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

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

thanks!

Upvotes: 2

Views: 1949

Answers (1)

Raz Luvaton
Raz Luvaton

Reputation: 3780

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

Only if you do the new Chart(...)

graphData as parameter to the canvas is great

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

jsFiddle

Upvotes: 2

Related Questions