d3.js: Histogram not rendering if domain does not start with 0 (means [0, *])

StackOverflow https://stackoverflow.com/questions/23662770

  •  22-07-2023
  •  | 
  •  

سؤال

I am new to d3.js and asking myself why the following histogram does not render. It is based upon the simple histogram demo from http://bl.ocks.org/mbostock/3048450 whereby the only significant difference is the domain of the x scale: it does not start with 0 but with 10. Changing the range makes it work.

(I'm not allowed to post the last link)

var numOfBins = 10;
var values = [10, 55, 60, 90, 95];

// A formatter for counts.
var formatCount = d3.format(",.0f");

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

var x = d3.scale.linear()
    .domain([
        Math.floor(d3.min(values) / numOfBins) * numOfBins, // 10
        Math.ceil(d3.max(values) / numOfBins) * numOfBins // 100
    ])
    .range([0, width]);

// Generate a histogram using numOfBins uniformly-spaced bins.
var data = d3.layout.histogram()
    .bins(x.ticks(numOfBins))
    (values);

var y = d3.scale.linear()
    .domain([0, d3.max(data, function(d) { return d.y; })])
    .range([height, 0]);

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

var svg = d3.select("body").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 bar = svg.selectAll(".bar")
    .data(data)
  .enter().append("g")
    .attr("class", "bar")
    .attr("transform", function(d) { return "translate(" + x(d.x) + "," + y(d.y) + ")"; });

bar.append("rect")
    .attr("x", 1)
    .attr("width", x(data[0].dx) - 1)
    .attr("height", function(d) { return height - y(d.y); });

bar.append("text")
    .attr("dy", ".75em")
    .attr("y", 6)
    .attr("x", x(data[0].dx) / 2)
    .attr("text-anchor", "middle")
    .text(function(d) { return formatCount(d.y); });

svg.append("g")
    .attr("class", "x axis")
    .attr("transform", "translate(0," + height + ")")
    .call(xAxis);
هل كانت مفيدة؟

المحلول

The problem is the line that computes the width of the rect elements:

.attr("width", x(data[0].dx) - 1)

When the domain starts at 10, this value is -1, which is not a valid width. To fix, compute the width of a rectangle in a different way, e.g. by dividing the total width by the number of bins:

.attr("width", width/numOfBins)

Complete demo here.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top