我试图让我的轴上的刻度线有条件格式。例如,如果它们是正数,我希望它们是绿色和红色,如果它们是负数。
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';
}
});
答案 0 :(得分:2)
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");
答案 1 :(得分:0)
您可以翻译成modern Javascript syntax,但要谨慎使用conditional chain并全部以人类可读的格式进行>
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");