Skip to content

Instantly share code, notes, and snippets.

@GitNoise
Last active December 5, 2016 09:38
Show Gist options
  • Save GitNoise/03f48f72669e452f4a36391b472ff9e9 to your computer and use it in GitHub Desktop.
Save GitNoise/03f48f72669e452f4a36391b472ff9e9 to your computer and use it in GitHub Desktop.
multimodal random
license: mit
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://d3js.org/d3-scale.v1.min.js"></script>
<script src="https://d3js.org/d3-array.v1.min.js"></script>
<script src="https://d3js.org/d3-random.v1.min.js"></script>
<style>
body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; }
circle.blue {
fill: blue;
}
circle.red {
fill: red;
}
circle.purple, .bar {
fill: purple;
}
</style>
</head>
<body>
<script>
var sampleSize = 10000;
var svg = d3.select("body").append("svg")
.attr("width", 960)
.attr("height", 700)
var scaleX = d3.scaleLinear()
.domain([1,100])
.range([100, 500]);
var randA = d3.randomNormal(25,10);
var dataA = Array.apply(null, new Array(sampleSize));
dataA = dataA.map(() => randA());
svg.append("g")
.selectAll('.blue')
.data(dataA)
.enter()
.append('circle')
.classed('blue', true)
.attr('cx', (d) => scaleX(d))
.attr('cy', 100)
.attr('r', 1)
var randB = d3.randomNormal(75,10);
var dataB = Array.apply(null, new Array(sampleSize));
dataB = dataB.map(() => randB());
svg.append("g")
.selectAll('.red')
.data(dataB)
.enter()
.append('circle')
.classed('red', true)
.attr('cx', (d) => scaleX(d))
.attr('cy', 200)
.attr('r', 1)
var randAB = () => Math.random() > 0.5 ? randA() : randB();
var dataAB = Array.apply(null, new Array(sampleSize));
dataAB = dataAB.map(() => randAB());
svg.append("g")
.selectAll('.purple')
.data(dataAB)
.enter()
.append('circle')
.classed('purple', true)
.attr('cx', (d) => scaleX(d))
.attr('cy', 300)
.attr('r', 1)
var histogram = d3.histogram()
.domain(scaleX.domain())
.thresholds(scaleX.ticks(50));
var bins = histogram(dataAB);
var scaleY = d3.scaleLinear()
.domain([0, d3.max(bins, (d) => d.length)])
.range([0, 100]);
svg.selectAll("rect")
.data(bins)
.enter()
.append("rect")
.attr("class", "bar")
.attr("x", (d) => scaleX(d.x0))
.attr("y", (d) => 450 - scaleY(d.length))
.attr("width", (d) => scaleX(d.x1) - scaleX(d.x0) - 1)
.attr("height", (d) => scaleY(d.length));
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment