block by timelyportfolio 8054b507faa94c89a09a379b605b0c7b

d3 kde using simple-statistics

Full Screen

Built with blockbuilder.org

Working on a d3v3 project where a density plot might be helpful. There are other examples out there. I wanted to try with the fantastic simple-statistics.

index.html

<!DOCTYPE html>
<head>
  <meta charset="utf-8">
  <script src="https://unpkg.com/simple-statistics@5.2.1/dist/simple-statistics.min.js"></script>
  <script src="https://d3js.org/d3.v3.min.js"></script>
  <style>
    body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; }
  </style>
</head>

<body>
  <script>
    var width = 960, height = 500
    var svg = d3.select("body").append("svg")
      .attr("width", width)
      .attr("height", height)
    	.append("g")
    		.attr("transform", "translate(100,0)")

    // from //bl.ocks.org/mbostock/4349187
    // Sample from a normal distribution with mean 0, stddev 1.
    function normal() {
      var x = 0,
          y = 0,
          rds, c;
      do {
        x = Math.random() * 2 - 1;
        y = Math.random() * 2 - 1;
        rds = x * x + y * y;
      } while (rds == 0 || rds > 1);
      c = Math.sqrt(-2 * Math.log(rds) / rds); // Box-Muller transform
      return x * c; // throw away extra sample y * c
    }
    
    var data = []
    for(var i = 0; i < 10000; i++) {
      data.push(normal())
    }
    
    var kde = ss.kernelDensityEstimation(data)
    
    var breaks = ss.equalIntervalBreaks(data, 100)
    
    var sc_x = d3.scale.linear()
    	.range([0, width - 100])
    var sc_y = d3.scale.linear()
    	.range([0, height])
    	.domain(d3.extent(breaks))
    
    var path = svg.append("path")
    	.attr("d", d3.svg.line().interpolate("basis")(
        breaks.map(function(d) {
          return [sc_x(kde(d)), sc_y(d)]
        })
      ))
    	.style("fill", "none")
    	.style("stroke", "black")
    
    svg.append("g")
      .call(d3.svg.axis().orient("left").scale(sc_y))
    	.selectAll("line,path")
    	.style("fill", "none")
    	.style("stroke", "black")
  </script>
</body>