user1855009
user1855009

Reputation: 971

Y-axis getting cut off/not scaling properly on d3 bar chart?

I can't figure out why my y-axis is getting cut off and my first bar is extending way out of range. From what I can tell, everything in the js file is correct. The code is below, but I also created a gist for it. Here's a link to the bl.ocks version.

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

Upvotes: 2

Views: 4815

Answers (1)

amakhrov
amakhrov

Reputation: 3939

This is a type issue. In your data file the 'students' field is string rather then numeric, hence the max value for the scale is calculated incorrectly (e.g. "2" > "10" in string comparison).

You either need to change your data structure (or do some data convertion after initial load) or convert it in the d3.max callback, like below:

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

Upvotes: 7

Related Questions