Skip to content

Instantly share code, notes, and snippets.

@jwilber
Last active January 14, 2019 06:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jwilber/a1b95bf25eb9a691b902f91d7126f245 to your computer and use it in GitHub Desktop.
Save jwilber/a1b95bf25eb9a691b902f91d7126f245 to your computer and use it in GitHub Desktop.
dot/circle normal distribution
license: mit
<!DOCTYPE html>
<meta charset="utf-8">
<body>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>
//SVG setup
const margin = {top: 10, right: 30, bottom: 30, left: 30},
width = 550 - margin.left - margin.right,
height = 480 - margin.top - margin.bottom;
const 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})`);
// datasource
const allData = d3.range(200).map( (d,i) => ({
Name: i,
Value: +d3.randomNormal(20, 3.5)().toFixed(1)
}));
//x scales
const x = d3.scaleLinear()
.domain(d3.extent(allData, d => +d.Value))
.rangeRound([0, width]);
//number of bins for histogram
const nbins = 30;
function moveToDistribution(){
//histogram binning
const histogram = d3.histogram()
.domain(x.domain())
.thresholds(x.ticks(nbins))
.value(d => +d.Value);
//binning data and filtering out empty bins
const bins = histogram(allData);
console.log(bins)
//g container for each bin
let binContainer = svg.selectAll("g.gBin")
.data(bins)
.enter()
.append("g" )
.attr("class", "gBin")
.attr("transform", d => `translate(${x(d.x0)}, ${height})`)
.selectAll("circle")
.data(d => d.map((p, i) => {
return {value: p.Value,
radius: (x(d.x1)-x(d.x0))/2.5}
}))
.enter()
.append("circle")
.attr("class", "enter")
.attr("cx", 0) //g element already at correct x pos
.attr("cy", (d, i) => {
return - i * 2 * d.radius - d.radius})
.attr("r", d => d.radius);
// add x axis
svg.append("g")
.attr("class", "axis axis--x")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x));
};//moveToDistribution
//draw everything
moveToDistribution();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment