Amir Rahbaran
Amir Rahbaran

Reputation: 2430

D3.js version 4: How to properly set the x-axis-intervals for a histogram

I grabbed this code from here and just modified the data variable:

<!DOCTYPE html>
<meta charset="utf-8">
<style>

.bar rect {
  fill: steelblue;
}

.bar text {
  fill: #fff;
  font: 10px sans-serif;
}

</style>
<svg width="960" height="500"></svg>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>

var data = [1,1,1,1, 2,2,2,2,2, 4,4, 5, 6,6,6, 7,7,7, 9,9,9, 12,12,12,12,12,12,12];

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

var svg = d3.select("svg"),
    margin = {top: 10, right: 30, bottom: 30, left: 30},
    width = +svg.attr("width") - margin.left - margin.right,
    height = +svg.attr("height") - margin.top - margin.bottom,
    g = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");

var x = d3.scaleLinear()
    .rangeRound([0, width]);

var bins = d3.histogram()
    //.domain([0,12])
    .domain(x.domain())
    .thresholds(x.ticks(10))
    (data);

var y = d3.scaleLinear()
    .domain([0, d3.max(bins, function(d) { return d.length; })])
    .range([height, 0]);

var bar = g.selectAll(".bar")
  .data(bins)
  .enter().append("g")
    .attr("class", "bar")
    .attr("transform", function(d) { return "translate(" + x(d.x0) + "," + y(d.length) + ")"; });

bar.append("rect")
    .attr("x", 0.5)
    .attr("width", x(bins[0].x1) - x(bins[0].x0) - 1)
    .attr("height", function(d) { return height - y(d.length); });

bar.append("text")
    .attr("dy", ".75em") // why?
    .attr("y", 6)
    .attr("x", (x(bins[0].x1) - x(bins[0].x0)) / 2)
    .attr("text-anchor", "middle")
    .text(function(d) { return formatCount(d.length); });

g.append("g")
    .attr("class", "axis axis--x")
    .attr("transform", "translate(0," + height + ")")
    .call(d3.axisBottom(x));

</script>

My chart looks like this: enter image description here

I tried to change it to d3.histogram().domain([0,12]) or play around with the threshhold but still no luck. The console prints

My goal:

  1. Bins should be an array with eight arrays (as data has eight unique values).
  2. Display the bins with a correct x-axis

Upvotes: 1

Views: 701

Answers (1)

Cyril Cherian
Cyril Cherian

Reputation: 32327

You will need to set the domain of x axis:

var x = d3.scaleLinear()
    .domain([0,12]) //you have not defined the domain
    .rangeRound([0, width]);

working code here

Upvotes: 2

Related Questions