Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

JavaScript

Babel is required to process package imports. If you need a different preprocessor remove all packages first.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <div class="container">
  <div class="row">
    <div class="col-sm-6">
      <div id="chart"></div>
    </div>
    <div class="col-sm-6">
      <div class="row">
        <button type="button" class="btn btn-xs" id="new_button">Generate Data</button>
        <button type="button" class="btn btn-xs" id="cluster_button">Cluster</button>
        <button type="button" class="btn btn-xs" id="clean_button">Clear</button>
      </div>
    </div>
  </div>
</div>
              
            
!

CSS

              
                body {
  background-color: #555;
  margin-top: 10px;
}

#chart {
  background-color: #555;
}

.row {
  padding-top: 2px;
}

.circle {
  stroke: #000;
  stroke-width: 1px;
  fill: #ccc;
  fill-opacity: 1;
}

.line {
  stroke: #000;
  stroke-width: 1px;
}

              
            
!

JS

              
                var size = 400; //The size of the canvas
var margin_size = 50;
var point_size = 5;

var colors = d3.scaleOrdinal(d3.schemeCategory10);
var domain_max = 1000;

var density_generation_mode = false;
var density_ratio = 0.3;

var eps = 150; // minimal distance to form a cluster
var minpts = 3; // minimal number of points
var iterations = 10;

var points = [];

var xScale = undefined;
var yScale = undefined;

var delay = 0;
var delay_diff = 1000;
var duration = 1000;

var root_id = "layer0";
var category = undefined;

function drawCircle(container, p, r, color) {
  var circle = container
    .append("circle")
    .attr("cx", p.x)
    .attr("cy", p.y)
    .attr("r", r)
    .classed("circle", true);

  if (color) {
    circle.style("fill", color);
  }
  return circle;
}

function drawLine(container, p1, p2) {
  var line = container
    .append("line")
    .attr("x1", p1.x)
    .attr("y1", p1.y)
    .attr("x2", p2.x)
    .attr("y2", p2.y)
    .classed("line", true);
  return line;
}

function clean() {
  data = [];
  delay = 0;
  $(".circle").remove();
  $(".line").remove();
}

function new_category() {
  if (category == undefined) {
    category = 0;
  } else {
    category = category + 1;
  }
  return category;
}

function init() {
  delay = 0;
  points.map(function(point) {
    point.visited = false;
    point.el.style("fill", "#ccc");
  });
}

function get_distance(p1, p2) {
  var d = Math.sqrt(Math.pow(p2.x - p1.x, 2) + Math.pow(p2.y - p1.y, 2));
  return d;
}

function clean() {
  points = [];
  delay = 0;
  $(".circle").remove();
  d3.select("#chart").selectAll("g").on("click", null);
}

function get_unvisited() {
  var i = 0,
    length = points.length;

  for (; i < length; i++) {
    if (!points[i].visited) {
      return points[i];
    }
  }

  return undefined;
}

function get_cluster_points(p) {
  var in_cluster_points = [];
  points.map(function(d) {
    if (d !== p) {
      var distance = get_distance(d.data, p.data);
      if (distance < eps) {
        in_cluster_points.push(d);
      }
    }
  });
  return in_cluster_points;
}

function get_cluster_distance(cluster, p) {
  var distances = [];
  cluster.data.map(function(cp) {
    var distance = get_distance(cp.data, p.data);
    distances.push(distance);
  });

  return Math.min.apply(Math, distances);
}

function update_cluster(cluster) {
  var un_visitied_points = points.filter(function(point) {
    return point.visited == false;
  });

  var need_update = false;

  un_visitied_points.map(function(point) {
    var distance = get_cluster_distance(cluster, point);
    if (distance < eps) {
      point.visited = true;
      cluster.data.push(point);
      point.el
        .transition()
        .delay(delay)
        .duration(duration)
        .style("fill", colors(cluster.category));
      need_update = true;
      delay = delay + delay_diff;
    }
  });

  if (need_update) {
    update_cluster(cluster);
  }
}

function dbscan() {
  for (var i = 0; i < iterations; i++) {
    var p = get_unvisited();
    if (p == undefined) {
      break;
    }

    var in_cluster_points = get_cluster_points(p);
    if (in_cluster_points.length < minpts) {
      continue;
    }

    p.visited = true;
    var cluster = {};
    cluster.data = [];
    cluster.category = new_category();

    cluster.data.push(p);
    p.el
      .transition()
      .delay(delay)
      .duration(duration)
      .style("fill", colors(cluster.category));
    delay = delay + delay_diff;

    in_cluster_points.map(function(point) {
      cluster.data.push(point);
      point.visited = true;
      point.el
        .transition()
        .delay(delay)
        .duration(duration)
        .style("fill", colors(cluster.category));
    });
    delay = delay + delay_diff;

    update_cluster(cluster);
  }
}

$(function() {
  var margin = {
    top: margin_size,
    right: margin_size,
    bottom: margin_size,
    left: margin_size
  },
    width = size - margin.left - margin.right,
    height = size - margin.top - margin.bottom;

  var root = d3
    .select("#chart")
    .append("svg")
    .attr("width", size)
    .attr("height", size);

  var g = root
    .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")")
    .attr("id", root_id);

  //Draw Axis
  xScale = d3.scaleLinear().rangeRound([0, width]);
  yScale = d3.scaleLinear().rangeRound([height, 0]);

  xScale.domain([0, domain_max]);
  yScale.domain([0, domain_max]);

  g
    .append("g")
    .attr("transform", "translate(0," + height + ")")
    .call(d3.axisBottom(xScale));

  g.append("g").call(d3.axisLeft(yScale));

  function add_data(coords) {
    var mapped_coords = [coords[0] - margin_size, coords[1] - margin_size];
    var newData = {
      x: Math.round(xScale.invert(mapped_coords[0])),
      y: Math.round(yScale.invert(mapped_coords[1]))
    };

    var point = drawCircle(
      g,
      { x: mapped_coords[0], y: mapped_coords[1] },
      point_size
    );

    var p = {};
    p.data = newData;
    p.el = point;
    p.visited = false;
    points.push(p);
  }

  // Generate Data
  $("#new_button").click(function() {
    clean();
    if (density_generation_mode) {
      root.on("mousemove", function() {
        var coords = d3.mouse(this);
        if (d3.event.ctrlKey && Math.random() < density_ratio) {
          for (var i = 0; i < minpts; i++) {
            var distance = Math.random() * eps / domain_max;
            var direction = Math.random() * Math.PI * 2;
            var new_p = [
              coords[0] + distance * Math.cos(direction),
              coords[1] + distance * Math.cos(direction)
            ];
            add_data(new_p);
          }
        }
      });
    } else {
      root.on("click", function() {
        var coords = d3.mouse(this);
        add_data(coords);
      });
    }
  });

  $("#cluster_button").click(function() {
    init();
    dbscan();
  });

  $("#clean_button").click(function() {
    clean();
  });
});

              
            
!
999px

Console