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 Settings

Here you can Sed posuere consectetur est at lobortis. Donec ullamcorper nulla non metus auctor fringilla. Maecenas sed diam eget risus varius blandit sit amet non magna. Donec id elit non mi porta gravida at eget metus. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.

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 class="row">
        <label for="k_input">K</label>
        <input type="text" id="k_input" placeholder="3">
      </div>
    </div>
  </div>
</div>
              
            
!

CSS

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

input {
  width: 30px;
}

#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 center_size = 10;
var colors = d3.scaleOrdinal(d3.schemeCategory10);
var domain_max = 1000;
var data = [];
var k = 3; // K in K-means
var iterations = 3; // number of interations for kmean

var points = [],
  center_points = [];

var xScale = undefined;
var yScale = undefined;

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

var root_id = "layer0";

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 = [];
  $(".circle").remove();
  $(".line").remove();
}

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 random_centers() {
  var i = 0;
  var results = [];
  for (; i < k; i++) {
    var result = {};
    result.x = Math.random() * domain_max;
    result.y = Math.random() * domain_max;
    results.push(result);
  }
  return results;
}

function init_center(container) {
  var i = 0,
    length = k;
  var centers = random_centers();
  for (; i < k; i++) {
    var center = centers[i];
    var center_mapped = {x : xScale(center.x), y : yScale(center.y)};
    var point = drawCircle(container, center_mapped, center_size, colors(i));
    var p = {};
    p.data = center;
    p.label = i;
    p.el = point;
    center_points.push(p);
  }
}

function label_points(targets, centers) {
  targets.map(function(item) {
    var i = 0;
    var distances = [];
    // using unmapped data for distance caculating
    for (; i < k; i++) {
      var distance = get_distance(item.data, centers[i].data);
      var label = centers[i].label;
      distances.push([distance, label]);
    }

    distances.sort(function(a, b) {
      return a[0] - b[0];
    });

    item.label = distances[0][1];
    item.el.transition().delay(delay).duration(duration).style("fill", colors(item.label));
  });
  delay = delay + delay_diff;
}

function update_centers(points, centers) {
  var i = 0;
  for (; i < k; i++) {
    var group_points = points.filter(function(v) {
      return v.label == i;
    });
    var j = 0,
      length = group_points.length;
    if (length > 0) {
      var x = 0,
        y = 0;
      for (; j < length; j++) {
        x = x + group_points[j].data.x;
        y = y + group_points[j].data.y;
      }
      x = x / length;
      y = y / length;
      centers[i].data.x = x;
      centers[i].data.y = y;
      centers[i].el.transition().delay(delay).duration(duration).attr("cx", xScale(x)).attr("cy", yScale(y));
    }
    delay = delay + delay_diff;
  }
}

function init_kmean() {
  center_points.map(function(p){
    var el = p.el.node();
    $(el).remove();
  });
  center_points = [];
  
  points.map(function(p){
    p.el.style("fill", "#ccc");
  });
  
  delay = 0;
}

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

$(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));

  // Generate Data
  $("#new_button").click(function() {
    clean();
    root.on("click", function() {
      var coords = d3.mouse(this);
      var mapped_coords = [coords[0] - margin_size, coords[1] - margin_size];
      var newData = {
        x: Math.round(xScale.invert(mapped_coords[0])), // Takes the pixel number to convert to number
        y: Math.round(yScale.invert(mapped_coords[1]))
      };

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

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

  $("#cluster_button").click(function() {
    init_kmean();
    init_center(g);
    for ( var i = 0; i < iterations; i++) {
      label_points(points, center_points);
      update_centers(points, center_points);
    }
  });
  
  $("#k_input").change(function(){
    k = $(this).val();
  });
  
  $("#clean_button").click(function() {
    clean();
  });
});

              
            
!
999px

Console