d3js:替换X轴

时间:2017-11-01 10:26:15

标签: javascript d3.js axes

我有一个气泡图,如下所示:

enter image description here

我使用的数据格式如下:

 var data = [{name: "A", rank: 1, student_percentile: 100.0, 
         admit_probability: 24},
        {name: "B", rank: 45, student_percentile: 40.3, 
         admit_probability: 24},
        {name: "C", rank: 89, student_percentile: 89.7, 
         admit_probability: 24},
        {name: "D", rank: 23, student_percentile: 10.9, 
         admit_probability: 24},
        {name: "E", rank: 56, student_percentile: 30.3, 
         admit_probability: 24},
         {name: "F", rank: 34, student_percentile: 110, 
         admit_probability: 84}];

对于输入中的某些值,我没有正确的百分位值,所以我默认放置110.现在,我想绘制这些值并在X轴上而不是110,我想显示& #34; NAN&#34 ;.例如,Here" F"将X轴值设为110.因此,我想将该值标记为" NAN"。

如何更换X轴上的值?

我的脚本如下:

var xscale = d3.scaleLinear()
        .domain(
                d3.extent(data, function(d) { return +d.student_percentile; })
            )
        .nice() 
        .range([0, width]);

    var yscale = d3.scaleLinear()
        .domain(d3.extent(data, function(d) { return +d.rank; }))
        .nice()
        .range([height, 0]);

    var xAxis = d3.axisBottom().scale(xscale);

    var yAxis = d3.axisLeft().scale(yscale);

1 个答案:

答案 0 :(得分:2)

使用tickFormat更改该特定值:

.tickFormat(function(d) {
    return d === 110 ? "NAN" : d
})

这是一个演示:

var svg = d3.select("svg");

var scale = d3.scaleLinear()
  .domain([0, 110])
  .range([20, 480]);

var axis = d3.axisBottom(scale)
  .tickFormat(function(d) {
    return d === 110 ? "NAN" : d
  })

svg.append("g").attr("transform", "translate(0,50)")
  .call(axis)
<script src="https://d3js.org/d3.v4.min.js"></script>
<svg width="500" height="100"></svg>