Skip to content

Instantly share code, notes, and snippets.

@ninjaPixel
Last active August 29, 2015 14:07
Show Gist options
  • Save ninjaPixel/747e4c0c002ce2caf342 to your computer and use it in GitHub Desktop.
Save ninjaPixel/747e4c0c002ce2caf342 to your computer and use it in GitHub Desktop.
histogram test
{"description":"histogram test","endpoint":"","display":"svg","public":true,"require":[],"fileconfigs":{"inlet.js":{"default":true,"vim":false,"emacs":false,"fontSize":12},"_.md":{"default":true,"vim":false,"emacs":false,"fontSize":12},"config.json":{"default":true,"vim":false,"emacs":false,"fontSize":12}},"fullscreen":false,"play":false,"loop":false,"restart":false,"autoinit":true,"pause":true,"loop_type":"pingpong","bv":false,"nclones":15,"clone_opacity":0.4,"duration":3000,"ease":"linear","dt":0.01,"ajax-caching":true,"thumbnail":"http://i.imgur.com/w0qZ8PO.png"}
// Generate a distribution of 10 random variables.
var values = d3.range(1000).map(d3.random.normal(3));
//console.log(values);
// A formatter for counts.
var formatCount = d3.format(",.0f");
var margin = {top: 10, right: 30, bottom: 30, left: 30},
width = 589 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var maxAbsValue = d3.max(values, function(d){return Math.abs(d); });
console.log('max abs',maxAbsValue);
var extentX = d3.extent(values);
var x = d3.scale.linear()
.domain([-maxAbsValue,maxAbsValue])
.range([0, width]);
// Generate a histogram using twenty uniformly-spaced bins.
var data = d3.layout.histogram()
.bins(x.ticks(20))
(values);
console.log('data', data);
var extentY = d3.extent(data, function(d){return d.length;});
var y = d3.scale.linear()
.domain([0, extentY[1]])
.range([height, 0]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
var svg = d3.select("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);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment