Skip to content

Instantly share code, notes, and snippets.

Created April 14, 2016 13:54
Show Gist options
  • Save anonymous/be1b4d11d420bcfc76a6a2005d0b2fe5 to your computer and use it in GitHub Desktop.
Save anonymous/be1b4d11d420bcfc76a6a2005d0b2fe5 to your computer and use it in GitHub Desktop.
1D Frequency Distribution Using Semitransparency
license: gpl-3.0
height: 100

Sample 1-dimensional frequency distribution by drawing one semitransparent rectangle for each data point. Adapted from mbostock's block.

<!DOCTYPE html>
<html>
<meta charset="utf-8">
<style>
body {
font: 10px sans-serif;
}
.bar rect {
fill: black;
shape-rendering: crispEdges;
}
.axis path, .axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
</style>
<body>
<script src="https://d3js.org/d3.v3.min.js"></script>
<script>
// Generate a Bates distribution of 10 random variables.
var values = d3.range(250).map(d3.random.bates(10));
// A formatter for counts.
var formatCount = d3.format(",.0f");
var barWidth = 10;
var margin = {top: 10, right: 30, bottom: 30, left: 30},
width = 960 - margin.left - margin.right,
height = 100 - margin.top - margin.bottom;
var x = d3.scale.linear()
.domain([0, 1])
.range([0, width]);
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(values)
.enter().append("g")
.attr("class", "bar")
.attr("transform", function(d) { return "translate(" + x(d) + ",0)"; });
bar.append("rect")
.attr("x", -barWidth/2)
.attr("width", barWidth )
.attr("height", 50)
.style("opacity", 0.1)
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment