2016-04-28 89 views
0

首先,直方图不能正确缩放,我知道这与dx值有关,但无法弄清楚。其次,我想要将x轴的线性()改为log(log.base(2))。当我这样做,我得到D3.js缩放和使用对数刻度

d3.v3.min.js:1 Error: Invalid value for <rect> attribute x="NaN" 
d3.v3.min.js:1 Error: Invalid value for <rect> attribute width="NaN" 
d3.v3.min.js:1 Error: Invalid value for <text> attribute y="NaN" 
d3.v3.min.js:1 Error: Invalid value for <text> attribute dx="NaN" 

直播>https://jsfiddle.net/akhiforu/3pnp4tne/1/

var t2 = [20215,16103,45455,14985,256670,13188,15328,49491,63460,34423,56615,16392,516284,88574,27766,43698,44305,101564,4481,101759,9127,51829,37063,18836,23825,5917,20652,84395,26395,168068,20444,118011,16853,19410,28493,80160,135780,41298,15050,4522,956406,45379,37417,35563,182006,87470,7335,40958,43437,70482,13675,195163,17662,161188,14333,63379,16437,41579,115290,86759,20540,29509,30362,21398,103527,15694,133251,395118,52066,24178,169511,73608]; 
var w = 700; 
    var h = 500; 
    var p = 50; 
    var thresholds = [0,20000,40000,60000,80000,100000,1000000]; 
    var hpop = []; 

    htemp = t2; 
    hpop = htemp.sort(function(a, b) { 
     return a - b; 
    }); 

    console.log(hpop); 

    var hdata = d3.layout.histogram() 
    .bins(thresholds) 
    (hpop) 
    console.log(hdata); 

    var y = d3.scale.linear() 
     .domain([0, d3.max(hdata.map(function(i){return i.length;}))]) 
     .range([0, h]); 

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

    console.log(d3.max(hpop)); 

    var xAxis = d3.svg.axis() 
     .scale(x) 
     .orient("bottom") 
     .tickFormat(d3.format("s")); 

    var histo = d3.select("#hist").append("svg") 
     .attr("width", w) 
     .attr("height", h + p) 
     .append("g") 
     .attr("transform", "translate(20,0)"); 

    histo.append("g") 
     .attr("transform", "translate(0," + h + ")") 
     .attr ("class", "axis") 
     .call(xAxis); 

    var hbar = histo.selectAll(".hbar") 
     .data(hdata) 
     .enter() 
     .append("g"); 

    hbar.append("rect") 
     .attr("x", function(d){return x(d.x);}) 
     .attr("y",function(d){return h - y(d.y);}) 
     .attr("width", function(d){return x(d.dx);}) 
     .attr("height", function(d){return y(d.y);}) 
     .attr("fill", "blue"); 

    hbar.append("text") 
     .attr("x", function(d){return x(d.x);}) 
     .attr("y",function(d){return h - y(d.y);}) 
     .attr("dy", "20px") 
     .attr("dx", function(d){return x(d.dx)/2;}) 
     .attr("fill", "#fff") 
     .attr("text-anchor", "middle") 
     .text(function(d){return d.y;}); 

谁能告诉我是什么问题..?

更新:感谢您的快速头脑风暴我用新的尺度重写了代码。 enter image description here

回答

3

为什么NaN

你越来越NaN的原因,我们不能对数尺度的领域包括:0(日志(0)为-Infinity

这里是例如日志

var x = d3.scale.log() 
    .domain([2, 8]) 
    .range([0, 100]) 
    .base(2) 


console.log(x(2)) => 0 
console.log(x(4)) => 50 
console.log(x(8)) => 100 

比例尺

我认为你目前的规模是正确的,但不是你真正想要的吗?你能给更多的描述吗?

+0

只是为了数学上正确,当x趋近于0时的log(x)是负无穷大,或者在javascript'negative_infinity'中。 –

+0

@GerardoFurtado谢谢,纠正。 –

+0

非常感谢你的解释,我能够包装这个东西。 –