Sammy
Sammy

Reputation: 84

Dynamic colours in chartJS based on entries in the array

I have an issue trying to color my bar chart dynamically based on a JSON response.

I know this has been asked a number of times before but none of the answers I've found or tried to work thorugh have got me any closer to a solution.

I've created a quick JSfiddle to show the issue.

I have a number of other charts which are all generated from different JSON strings so have cut this down a lot to try and isolate the issue. I don't have the same problem with the other charts as the number of entries in the Label array in consistent with the number of colours. The offending piece of code is this;

DT_Labels.forEach(function(DT_LABELS, x) {
data.datasets.push({
    label: DT_LABELS,
    backgroundColor: backgroundColor[x],
    data: JSON.parse(DT_Values[x]).map(Number)
            });
            });

DT_Labels only contains a single entry as the chart is a summarised list - In theory, this would work if I counted the number of DT_Values but if I do that, I can't get the correct data in the chart.

Any ideas how I can reformat this to generate the colours counter based on the number of Values instead of Labels?

Upvotes: 3

Views: 2515

Answers (1)

timclutton
timclutton

Reputation: 13004

Change:

backgroundColor: backgroundColor[x],

to:

backgroundColor: backgroundColor,

Result:

Result of code change

Why does this work?

The backgroundColor property can be specified in a number of ways. Typically it's set to a string, e.g. #abcdef but it can also be set to an array. In this case Chart.js itself will pick the colour from the array based on the index of the data point it is drawing.

Upvotes: 1

Related Questions