Jeff K
Jeff K

Reputation: 543

D3 Bar Chart Columns Overflowing

I am having an issue using d3 to create a bar chart where the column overflows the and the y axis labels are incorrect. Here is a fiddle http://jsfiddle.net/fajgvj9v/ that shows the issue. The data is parsing the <pre id="data"> tag to simulate a CSV I am using. If you change the value of 'a' to 5000 from 4000 it renders as expected.

<pre id="data">
name,count
a, 4000
b, 500
</pre>

yTitle = "Items";

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

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

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

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

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

var svg = d3.select("#malware_by_os").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 + ")");

var data = d3.csv.parse( d3.select("pre#data").text() );
console.log(data);
  var xLbl = d3.keys(data[0])[0];
  var yLbl = d3.keys(data[0])[1];

  data.sort(function(a, b) {
    return b[yLbl] - a[yLbl];
  });
  x.domain(data.map(function(d) {
    return d[xLbl];
  }));
  y.domain([0, d3.max(data, function(d) {
    return d[yLbl];
  })]);

  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(yTitle);

  svg.selectAll(".bar")
    .data(data)
    .enter().append("rect")
    .attr("class", "bar")
    .attr("x", function(d) {
      return x(d[xLbl]);
    })
    .attr("width", x.rangeBand())
    .attr("y", function(d) {
      return y(d[yLbl]);
    })
    .attr("height", function(d) {
      return height - y(d[yLbl]);
    });

Upvotes: 0

Views: 414

Answers (1)

Jeff K
Jeff K

Reputation: 543

The max function needs to convert to a number using +

  y.domain([0, d3.max(data, function(d) {
    return d[yLbl];
  })]);

should be

  y.domain([0, d3.max(data, function(d) {
    return +d[yLbl];
  })]);

Upvotes: 1

Related Questions