2013-08-08 6 views
2

y 축이 잘 리거나 첫 번째 막대가 범위를 벗어나는 이유를 알 수 없습니다. 내가 말할 수있는 것부터, js 파일의 모든 것이 정확합니다. 이 코드는 아래에 있지만, 그것에 대한 요점도 만들었습니다. 다음은 link to the bl.ocks version입니다.Y 축은 d3 막 대형 차트에서 제대로 잘라지지 않습니까?

var data; 

var margin = {top: 20, right: 20, bottom: 30, left: 80}, 
    width = 830 - margin.left - margin.right, 
    height = 500 - margin.top - margin.bottom; 

var formatPercent = d3.format(",.0f"); 

var x = d3.scale.ordinal() 
    .rangeRoundBands([0, width], .1); 

var y = d3.scale.linear() 
    .range([height, 0]); 

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

var yAxis = d3.svg.axis() 
    .scale(y) 
    .orient("left") 
    .tickFormat(formatPercent); 

var svg = d3.select("#bar").append("svg") 
    .attr("width", width + margin.left + margin.right) 
    .attr("height", height + margin.top + margin.bottom) 
.append("g") 
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); 

d3.json("../data/hopeNums.json", function(json) { 
data = json; 
x.domain(data.map(function(d) { return d.college; })); 
y.domain([0, d3.max(data, function(d) { return d.students; })]); 

svg.append("g") 
    .attr("class", "x axis") 
    .attr("transform", "translate(0," + height + ")") 
    .call(xAxis); 

svg.append("g") 
    .attr("class", "y axis") 
    .call(yAxis) 
.append("text") 
    .attr("transform", "rotate(-90)") 
    .attr("y", 6) 
    .attr("dy", ".71em") 
    .style("text-anchor", "end") 
    .text("Students"); 

svg.selectAll(".bar") 
    .data(json) 
.enter().append("rect") 
    .attr("class", "bar") 
    .attr("id", function(d) { return (d.id); }) 
    .attr("x", function(d) { return x(d.college); }) 
    .attr("width", x.rangeBand()) 
    .attr("y", function(d) { return y(d.students); }) 
    .attr("height", function(d) { return height - y(d.students); }); 

svg.selectAll("rect") 
    .on("click", function(d) { d3.select(this).style({fill: '#FAAE0A', stroke: '#F08C00', opacity:'0.5', 'stroke-width':'3px'})}); 

}); 

function type(d) { 
    d.students = +d.students; 
    return d; 
} 

답변

7

이것은 유형 문제입니다. 데이터 파일에서 'students'필드는 숫자가 아닌 문자열이며, 따라서 스케일의 최대 값이 잘못 계산됩니다 (예 : 문자열 비교에서 "2"> "10").

y.domain([0, d3.max(data, function(d) { return +d.students; })]); // note the '+' 
+0

총 감각을 만듭니다 :

당신이 중 하나는 다음과 같은 데이터 구조를 변경 (또는 할 초기로드 후 일부 데이터 convertion를) 또는 d3.max 콜백에서 변환해야합니다. 고맙습니다! – user1855009

관련 문제