contour2

by jpeter06

HTML

<!-- Load d3.js -->
<script src="https://d3js.org/d3.v4.js"></script>

<!-- specific plugin -->
<script src="https://d3js.org/d3-array.v2.min.js"></script>
<script src="https://d3js.org/d3-contour.v2.min.js"></script>

<!-- Create a div where the graph will take place -->
<div id="my_dataviz"></div>

JavaScript

// set the dimensions and margins of the graph
var margin = {top: 20, right: 30, bottom: 30, left: 40},
    width = 460 - margin.left - margin.right,
    height = 400 - margin.top - margin.bottom;

// append the svg object to the body of the page
var svg = d3.select("#my_dataviz")
  .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 + ")");

var data =  [{ group: "C", x: "10.7",  y: "15.3"},
{  group: "A",  x: "9.1",  y: "15.3"},
{  group: "B",  x: "18.1",  y: "13"},
{  group: "B",  x: "1.1",  y: "1"},
{  group: "B",  x: "2.1",  y: "4"},
{  group: "B",  x: "1.1",  y: "9"},
{  group: "B",  x: "14.1",  y: "13"},
{  group: "A",  x: "10.1",  y: "12.5"}];

// read data
 function generar(data) {
  // Add X axis
  var x = d3.scaleLinear()
    .domain([0, 22])
    .range([ 0, width ]);
  svg.append("g")
    .attr("transform", "translate(0," + height + ")")
    .call(d3.axisBottom(x));

  // Add Y axis
  var y = d3.scaleLinear()
    .domain([0, 22])
    .range([ height, 0 ]);
  svg.append("g")
    .call(d3.axisLeft(y));

  // compute the density data
  var densityData = d3.contourDensity()
    .x(function(d) { return x(d.x); })   // x and y = column name in .csv input data
    .y(function(d) { return y(d.y); })
    .size([width, height])
    .bandwidth(18)    // smaller = more precision in lines = more lines
    (data)

  // Add the contour: several "path"
  svg
    .selectAll("path")
    .data(densityData)
    .enter()
    .append("path")
      .attr("d", d3.geoPath())
      .attr("fill", "none")
      .attr("stroke", "#69b3a2")
      .attr("stroke-linejoin", "round")
}
generar(data);