Skip to content

Instantly share code, notes, and snippets.

@tmcw
Created August 21, 2012 14:55
Show Gist options
  • Save tmcw/3416235 to your computer and use it in GitHub Desktop.
Save tmcw/3416235 to your computer and use it in GitHub Desktop.
kmeans wip
<!DOCTYPE html>
<html>
<head>
<script src="http://d3js.org/d3.v2.js"></script>
<style>
body { margin: 0; padding: 0; font:normal 12px/20px sans-serif; }
#vis { width: 640px; }
circle.control {
fill: #d23634;
}
text.controltext {
text-anchor:middle;
}
</style>
</head>
<body>
<div id='vis'>
<script src='kmeans-diagram.js'></script>
</div>
</body>
</html>
var w = 620,
h = 100,
t = 0.5,
delta = 0.01,
padding = 10,
points = [{x: 1, y: 0}, { x: 5, y: 0 }, { x: 10, y: 0 }],
n = 3,
orders = d3.range(2, n + 2);
var vis = d3.select("#vis").selectAll("svg")
.data(orders)
.enter().append("svg")
.attr("width", w + 2 * padding)
.attr("height", h + 2 * padding)
.append("g")
.attr("transform", "translate(" + padding + "," + padding + ")");
var xs = d3.scale.linear().range([0, w]).domain([0, 10]).clamp(true);
function x(d) { return xs(d.x); }
function y(d) { return d.y; }
vis.selectAll("circle.control")
.data(points)
.enter().append("circle")
.attr("class", "control")
.attr("r", 10)
.attr("cx", x)
.attr("cy", y)
.call(d3.behavior.drag()
.on("dragstart", function(d) {
this.__origin__ = [d.x, d.y];
})
.on("drag", function(d) {
d.x = xs.invert(d3.event.x);
vis.selectAll("circle.control")
.attr("cx", x);
vis.selectAll("text.controltext")
.attr("x", x)
.attr("y", y)
.text(function(d, i) { return d.x; });
})
.on("dragend", function() {
delete this.__origin__;
}));
vis.selectAll("text.controltext")
.data(points)
.enter().append("text")
.attr("class", "controltext")
.attr("dx", "0px")
.attr("dy", "25px")
.text(function(d, i) { return d.x; });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment