Reputation: 71
I am trying to get my ticks on my axis to have conditional formatting. For example, if their positive numbers I want them to be green and red if they are negative numbers.
var bonus_penalties = [ -1,-13,-5,0,5,10,15];
var bpAxisScale = d3.scale.linear()
.domain([0,6])
.range([bottom- 45, 45]);
var bpAxis = d3.svg.axis()
.scale(bpAxisScale)
.orient('right')
.tickFormat(function(d) { return bonus_penalties[d]});
var bp_axis = d3.select("#experienceView").append('svg:g')
.attr("transform", "translate(160,0)")
.attr('class', 'bp')
.call(bpAxis)
.style('fill', function(d) {
if(bonus_penalties[d] < 0){
return 'red';
} else {
return 'green';
}
});
Upvotes: 2
Views: 2221
Reputation: 13920
You can translate to modern Javascript syntax, but with some care, using conditional chain and all in human-readable format:
bp_axis.selectAll("text")
.style('fill', d =>
(bonus_penalties[d].key < 0)? 'red'
: bonus_penalties[d].key? 'green'
: 'black'
)
.attr('font-size',"10px")
.style("text-anchor", "middle");
Upvotes: 0
Reputation: 71
Lars Kitthoff gave the answer:
bp_axis.selectAll("text")
.style('fill', function(d) {
if(bonus_penalties[d].key == 0){
return 'black';
} else if(bonus_penalties[d].key < 0){
return 'red';
} else {
return 'green';
}
})
.attr('font-size',"10px")
.style("text-anchor", "middle");
Upvotes: 2