block by jfsiii 75a948bd4149404702dec7813f7861c5

Simple histogram using v4

Full Screen

This is a simple histogram written using d3.js v4.

This graph is part of the code samples for the update to the book D3 Tips and Tricks to version 4 of d3.js.

forked from d3noob‘s block: Simple histogram using v4

index.html

<!DOCTYPE html>
<meta charset="utf-8">
<style> /* set the CSS */

rect.bar { fill: steelblue; }

</style>
<body>

<!-- load the d3.js library -->    	
<script src="//d3js.org/d3.v4.min.js"></script>
<script>

// set the dimensions and margins of the graph
var margin = {top: 10, right: 30, bottom: 30, left: 40},
    width = 960 - margin.left - margin.right,
    height = 500 - margin.top - margin.bottom;

// parse the date / time
var parseDate = d3.timeParse("%d-%m-%Y");

// set the ranges
var x = d3.scaleTime()
          .domain([new Date(2010, 6, 3), new Date(2012, 0, 1)])
          .rangeRound([0, width]);
var y = d3.scaleLinear()
          .range([height, 0]);

// set the parameters for the histogram
var histogram = d3.histogram()
    .value(function(d) { return d.date; })
    .domain(x.domain())
    .thresholds(x.ticks(d3.timeMonth));

// append the svg object to the body of the page
// append a 'group' element to 'svg'
// moves the 'group' element to the top left margin
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 + ")");

// get the data
d3.csv("earthquakes.csv", function(error, data) {
  if (error) throw error;
window.earthquakes = data
  // format the data
  data
    .forEach(function(d) {
      d.date = parseDate(d.dtg);
  	})
  ;

  // group the data for the bars
  var bins = histogram(data);

  // Scale the range of the data in the y domain
  y.domain([0, d3.max(bins, function(d) { return d.length; })]);

  // append the bar rectangles to the svg element
  svg.selectAll("rect")
      .data(bins)
    .enter().append("rect")
      .attr("class", "bar")
      .attr("x", 1)
      .attr("transform", function(d) {
		  return "translate(" + x(d.x0) + "," + y(d.length) + ")"; })
      .attr("width", function(d) { return x(d.x1) - x(d.x0) -1 ; })
      .attr("height", function(d) { return height - y(d.length); });

  // add the x Axis
  svg.append("g")
      .attr("transform", "translate(0," + height + ")")
      .call(d3.axisBottom(x));

  // add the y Axis
  svg.append("g")
      .call(d3.axisLeft(y));
      
});

</script>
</body>