Built with blockbuilder.org
Last active
January 14, 2019 06:42
-
-
Save jwilber/a1b95bf25eb9a691b902f91d7126f245 to your computer and use it in GitHub Desktop.
dot/circle normal distribution
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
license: mit |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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