【问题标题】:D3.js axis tick conditional formattingD3.js 轴刻度条件格式
【发布时间】:2015-03-17 16:57:31
【问题描述】:

我正在尝试让我的坐标轴上的刻度具有条件格式。例如,如果它们的正数,我希望它们是绿色的,如果它们是负数,我希望它们是红色的。

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';
            }
    });

【问题讨论】:

  • 调用轴组件后选择text元素,然后应用代码中的样式。
  • 将图标添加到刻度的最佳方法是什么?例如锁定或解锁的图标?
  • 我会说你必须修改轴组件。

标签: javascript html css d3.js


【解决方案1】:

Lars Kitthoff 给出了答案:

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");

【讨论】:

    【解决方案2】:

    您可以翻译成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");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-24
      • 1970-01-01
      相关资源
      最近更新 更多