Reputation: 645
How to change the color of individual bar in a bar graph.
var chart = c3.generate({
data: {
columns: [
['data1', 30, 20, 50, 40, 60, 50]
],
type: 'bar',
colors: {
data1: '#ff0000'
},
color: function (color, d) {
return d.id && d.id === 'data1' ? d3.rgb(color).darker(d.value / 120) : color;
}
}
});
Here, all bars which have value greater than 45 should be green in color and those below 45 should be red in color.
Upvotes: 4
Views: 5247
Reputation: 13
In case this is helpful for someone, this codepen by Stefka Todorov shows how to change colours according to 'category'. Helpful for anyone trying to change colours of one or more bars, and simpler than using boolean.
(Sharing this because I came here looking for how to change colours of C3 bars, and could not change colours for multiple bars using the earlier suggested method.)
var chart = c3.generate({
bindto: '#uv-div',
size: {
height: 150
},
bar: {
width: 40
},
padding: {
left: 60
},
color: {
pattern: ['#FABF62', '#ACB6DD']
},
data: {
x: 'x',
columns:
[
['x', 'Category1', 'Category2'],
['value', 300, 400]
],
type: 'bar',
color: function(inColor, data) {
var colors = ['#FABF62', '#ACB6DD'];
if(data.index !== undefined) {
return colors[data.index];
}
return inColor;
}
},
axis: {
rotated: true,
x: {
type: 'category'
}
},
tooltip: {
grouped: false
},
legend: {
show: false
}
});
Upvotes: 0
Reputation: 41065
Just make data.colors.data1
a function, like so
var chart = c3.generate({
data: {
columns: [
['data1', 30, 20, 50, 40, 60, 50]
],
type: 'bar',
colors: {
data1: function(d) {
return (d.value >= 45) ? '#00ff00': '#ff0000';
}
}
},
legend: {
show: false
},
// take care of color in tooltip
tooltip: {
contents: function (d, defaultTitleFormat, defaultValueFormat, color) {
color = function() {
return (d[0].value >= 45) ? '#00ff00' : '#ff0000';
};
return chart.internal.getTooltipContent.call(this, d, defaultTitleFormat, defaultValueFormat, color)
}
}
});
I assumed 45 to be green by the way.
Fiddle - http://jsfiddle.net/vc1Lq1um/
Upvotes: 5