Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
51
rated 0 times [  52] [ 1]  / answers: 1 / hits: 21327  / 9 Years ago, wed, january 27, 2016, 12:00:00

I have been experimenting with d3.js bar chart, I want to change the color depending on the value of the y axis, how do I achieve this. I tried adding linear gradients but then I lose control over it.



The code I am working on is based on this: http://bost.ocks.org/mike/bar/


More From » d3.js

 Answers
11

Add the following attributes to adapt the color:





var data = [4, 8, 15, 16, 23, 42];

var width = 420,
barHeight = 20;

var x = d3.scale.linear()
.domain([0, d3.max(data)])
.range([0, width]);

var chart = d3.select(.chart)
.attr(width, width)
.attr(height, barHeight * data.length);

var bar = chart.selectAll(g)
.data(data)
.enter().append(g)
.attr(transform, function(d, i) {
return translate(0, + i * barHeight + );
});

bar.append(rect)
.attr(width, x)
// add this attribute to change the color of the rect
.attr(fill, function(d) {
if (d > 25) {
return red;
} else if (d > 10) {
return orange;
}
return yellow;
})
.attr(height, barHeight - 1);

bar.append(text)
.attr(x, function(d) {
return x(d) - 3;
})
.attr(y, barHeight / 2)
.attr(dy, .35em)
// add this attribute to change the color of the text
.attr(fill, function(d) {
if (d > 10) {
return white;
}
return black;
})
.text(function(d) {
return d;
});

.chart text {
font: 10px sans-serif;
text-anchor: end;
}

<script src=https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js></script>

<svg class=chart></svg>




[#63543] Sunday, January 24, 2016, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
uriahw

Total Points: 372
Total Questions: 93
Total Answers: 115

Location: Bahrain
Member since Fri, Sep 16, 2022
2 Years ago
;