Reputation: 291
I have a bar chart with some JSON data:
var chart = c3.generate({
data: {
type: 'bar',
json: [
{ 'indicator': 'X', 'total': 500 },
{ 'indicator': 'Y', 'total': 600 },
{ 'indicator': 'Z', 'total': 700 }
],
keys: {
x: 'indicator',
value: ['total']
}
},
axis: {
x: {
type: 'category'
}
},
bar: {
width: {
ratio: 0.5
}
},
color: {
pattern: ['#E39920', '#53B5B5', '#CD249A']
},
});
How can I change the color of each bar? I used the color pattern solution C3 has, but that makes all the bars the same as the first color of the pattern.
Upvotes: 1
Views: 1958
Reputation: 698
You need to define color for each bar in an array and use the color function to return the required color for each bar,
var cat_colors = ['#FF0000','#00FF00', '#0000FF']
var chart = c3.generate({
data: {
columns: [
['data1', 30, 20, 50],
],
type: 'bar',
color: function (color, d) {
return cat_colors[d.x];
}
}
})
;
https://jsfiddle.net/okhsu1nv/
Upvotes: 1
Reputation: 6207
The color function variation you're using colours the bars by series, and since all the data in the bars you have are in the series 'total' they will all have the same colour.
There are 2 options:
Firstly, what you can do is declare a color function inside the data declaration and use the .index to set a colour per bar - see http://jsfiddle.net/fu33b6em/1/ for the full fiddle
color: function (color, d) {
if (d.id) {
return ['#E39920', '#53B5B5', '#CD249A'][d.index % 3];
}
return "#000";
},
However, as you'll notice the series key at the bottom doesn't reflect these colours, it returns the default colour for the series 'total', which here is black, the "#000" in the code.
Your second alternative, is to declare a separate series per entry, i.e. totalX, totalY, totalZ and keep your original color function - http://jsfiddle.net/fu33b6em/2/
data: {
type: 'bar',
json: [
{ 'indicator': 'X', 'totalX': 100 },
{ 'indicator': 'Y', 'totalY': 200 },
{ 'indicator': 'Z', 'totalZ': 300 }
],
groups: [
["totalX", "totalY", "totalZ"],
],
keys: {
x: 'indicator',
value: ['totalX', 'totalY', 'totalZ'],
},
},
The groups
declaration is there to avoid gaps in the chart. i.e. X is missing data for totalY and totalZ but c3 will reserve space for bars for them. However, tell c3 they're grouped (stacked) series and space for just one bar will be reserved (totalY and totalZ will be zero-height stacked bars in the same column as totalX in this case)
Upvotes: 1