Skip to content

Instantly share code, notes, and snippets.

@lsquaredleland
Last active November 8, 2019 09:08
Show Gist options
  • Save lsquaredleland/7df3d6221e4edabf891f to your computer and use it in GitHub Desktop.
Save lsquaredleland/7df3d6221e4edabf891f to your computer and use it in GitHub Desktop.
Uniform Kernel Distribution

#Uniform Kernel Distribution: Try experimenting with changing the bandwidth value (h) and the grid_spacing, To see how the bubble sizes vary.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Uniform Kernel Distribution</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js" charset="utf-8"></script>
</head>
<body>
<label id="form" for="show-h">
Show Bandwidth
<input type="checkbox" id="show-h" disabled>
</label>
<div id="chartArea"></div>
<script src="js.js"></script>
</body>
</html>
var height = 500;
var width = 900;
var data = [];
var grid_spacing = 100;
var h = 75; //Cut off distance is the bandwidth for this type of kernel
for(var i = 0; i < 50; i++){
data.push([Math.random()*width, Math.random()*height]);
}
var svg = d3.select("#chartArea") //Uniform Kernel
.append("svg")
.attr("width", width)
.attr("height", height);
svg.selectAll('circle')
.data(data).enter()
.append('circle')
.attr('cx', function(d) { return d[0]; })
.attr('cy', function(d) { return d[1]; })
.attr('r', 5)
for(var wi = 0; wi <= width; wi+=grid_spacing){
svg.append('line')
.style('stroke', 'black')
.attr('x1', wi)
.attr('x2', wi)
.attr('y1', 0)
.attr('y2', height)
}
for(var hi = 0; hi <= height; hi+=grid_spacing){
svg.append('line')
.style('stroke', 'black')
.attr('x1', 0)
.attr('x2', width)
.attr('y1', hi)
.attr('y2', hi)
}
for(var x_i = 0; x_i <= width; x_i += grid_spacing){
for(var y_i = 0; y_i <= height; y_i += grid_spacing){
var summation = 0;
for(var i = 0; i < data.length; i++){
//Calculate Eulicidean distance
distance = Math.sqrt(Math.pow((x_i - data[i][0]),2) + Math.pow((y_i - data[i][1]),2))
if(distance < h)
summation++
}
//Shows the extent of the h
svg.append('circle')
.classed('h', true)
.style('fill', 'none')
.style('stroke', 'none')
.attr('cx', x_i)
.attr('cy', y_i)
.attr('r', h)
var lambda = 1/(Math.PI*h^2) * summation;
if(lambda > 0){
svg.append('circle')
.style('fill', 'none')
.style('stroke', 'maroon')
.attr('cx', x_i)
.attr('cy', y_i)
.attr('r', lambda*1000)
}
}
}
d3.select("#show-h")
.property("disabled", false)
.on("change", function() {
var currentColour = d3.selectAll('.h').style('stroke');
var nextColour = currentColour === 'rgb(28, 255, 152)' ? 'none' : 'rgb(28, 255, 152)';
d3.selectAll('.h').style('stroke', nextColour);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment