Skip to content

Instantly share code, notes, and snippets.

@bclinkinbeard
Last active September 6, 2016 19:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bclinkinbeard/a2fdce4d5b56d4563d4fef4292a90eda to your computer and use it in GitHub Desktop.
Save bclinkinbeard/a2fdce4d5b56d4563d4fef4292a90eda to your computer and use it in GitHub Desktop.
Personal Best High Jumps for Two High Jumpers
<!DOCTYPE HTML>
<html>
<head>
<title>Personal Best High Jumps for Two High Jumpers</title>
<script src="//d3js.org/d3.v3.min.js" charset="utf-8" type="text/javascript"></script>
<script src="//literasee.io/public/frame-init.js"></script>
<script src="xkcd.js"></script>
<style>
@font-face {
font-family: "xkcd";
src: url('//rawgit.com/shreyankg/xkcd-desktop/master/Humor-Sans.ttf');
}
body {
font-family: "xkcd", sans-serif;
font-size: 16px;
color: #333;
}
text.title {
font-size: 20px;
}
path {
fill: none;
stroke-width: 2.5px;
stroke-linecap: round;
stroke-linejoin: round;
}
path.axis {
stroke: black;
}
path.bgline {
stroke: white;
stroke-width: 6px;
}
</style>
</head>
<body>
<div id="chart"></div>
<script>
function responsivefy (svg) {
// get container + svg aspect ratio
var container = d3.select(svg.node().parentNode),
width = parseInt(svg.style('width')) / 1,
height = parseInt(svg.style('height')),
aspect = width / height;
// add viewBox and preserveAspectRatio properties,
// and call resize so that svg resizes on inital page load
svg.attr('viewBox', '0 0 ' + width + ' ' + height)
.attr('preserveAspectRatio', 'xMinYMid')
.call(resize);
// to register multiple listeners for same event type,
// you need to add namespace, i.e., 'click.foo'
// necessary if you call invoke this function for multiple svgs
// api docs: https://github.com/mbostock/d3/wiki/Selections#on
d3.select(window).on('resize.' + container.attr('id'), resize);
// get width of container and resize svg to fit it
function resize () {
var targetWidth = parseInt(container.style('width'));
svg.attr('width', targetWidth);
svg.attr('height', Math.round(targetWidth / aspect));
}
}
// Data for elite jumper Judy
function f1 (x) {
return 0.166667 * x + 6.416667;
}
// Data for novice jumper Anna
function f2 (x) {
return 0.5 * x + 3;
}
var xmin = 1,
xmax = 3,
N = 100,
data = d3.range(xmin, xmax, (xmax - xmin) / N).map(function (d) {
return {x: d, y: f1(d)};
})
data2 = d3.range(xmin, xmax, (xmax - xmin) / N).map(function (d) {
return {x: d, y: f2(d)};
});
// Build the plot.
var plot = xkcdplot();
plot('#chart');
// Add the lines.
plot.plot(data);
plot.plot(data2, {stroke: "red"});
// Render the image.
plot.xlim([0, 4]).draw();
responsivefy(d3.select('svg'));
</script>
</body>
</html>
Copyright (c) 2012–2013 Daniel Foreman-Mackey
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
function xkcdplot() {
// Default parameters.
var
margin = {top: 35, right: 0, bottom: 45, left: 0},
padding = {top: 30, right: 30, bottom: 30, left: 30},
outerWidth = 900,
outerHeight = 500,
innerWidth = outerWidth - margin.left - margin.right,
innerHeight = outerHeight - margin.top - margin.bottom,
width = innerWidth - padding.left - padding.right,
height = innerHeight - padding.top - padding.bottom,
arrowSize = 12,
arrowAspect = 0.4,
arrowOffset = 6,
magnitude = 0.003,
xlabel = "Track Season",
ylabel = "Height (Feet)",
xlabel1 = "Spring 2015",
xlabel2 = "Spring 2016",
anna2015 = "3 Feet, 6 Inches",
anna2016 = "4 Feet, 0 Inches",
judy2015 = "6 Feet, 7 Inches",
judy2016 = "6 Feet, 9 Inches",
judyname = "Judy",
annaname = "Anna",
title = "Personal Best High Jumps for Two High Jumpers",
xlim,
ylim = [-1, 8];
// Plot elements.
var el,
xscale = d3.scale.linear(),
yscale = d3.scale.linear();
// Plotting functions.
var elements = [];
// The XKCD object itself.
var xkcd = function (nm) {
el = d3.select(nm).append("svg")
.attr("width", width + 2 * margin.top)
.attr("height", height + 2 * margin.top)
.append("g")
.attr("transform", "translate(" + margin.left + ", "
+ margin.top + ")");
return xkcd;
};
// Getters and setters.
xkcd.xlim = function () {
if (!arguments.length) return xlim;
xlim = arguments[0];
return xkcd;
};
// Do the render.
xkcd.draw = function () {
// Set the axes limits.
xscale.domain(xlim).range([0, width]);
yscale.domain(ylim).range([height, 0]);
// Compute the zero points where the axes will be drawn.
var x0 = xscale(0.6),
y0 = yscale(0);
// Draw the axes.
var axis = d3.svg.line().interpolate(xinterp);
el.selectAll(".axis").remove();
el.append("svg:path")
.attr("class", "x axis")
.attr("d", axis([[210, y0], [630, y0]]));
el.append("svg:path")
.attr("class", "y axis")
.attr("d", axis([[x0, 0], [x0, height - 50]]));
// Laboriously draw some arrows at the ends of the axes.
var aa = arrowAspect * arrowSize,
o = arrowOffset,
s = arrowSize;
// el.append("svg:path")
// .attr("class", "x axis arrow")
// .attr("d", axis([[width - s + o, y0 + aa], [width + o, y0], [width - s + o, y0 - aa]]));
// el.append("svg:path")
// .attr("class", "x axis arrow")
// .attr("d", axis([[s - o, y0 + aa], [-o, y0], [s - o, y0 - aa]]));
el.append("svg:path")
.attr("class", "y axis arrow")
.attr("d", axis([[x0 + aa, s - o], [x0, -o], [x0 - aa, s - o]]));
el.append("svg:path")
.attr("class", "y axis arrow")
.attr("d", axis([[x0 + aa, height - 50 - s + o], [x0, height - 50 + o], [x0 - aa, height - 50 - s + o]]));
for (var i = 0, l = elements.length; i < l; ++i) {
var e = elements[i];
e.func(e.data, e.x, e.y, e.opts);
}
// Add some axes labels.
el.append("text").attr("class", "x label")
.attr("text-anchor", "middle")
.attr("x", width/2)
.attr("y", y0 + 25)
.attr("dy", ".75em")
.text(xlabel);
el.append("text").attr("class", "x label")
.attr("text-anchor", "middle")
.attr("x", 210)
.attr("y", y0 + 13)
.attr("dy", ".75em")
.text(xlabel1);
el.append("text").attr("class", "x label")
.attr("text-anchor", "middle")
.attr("x", 630)
.attr("y", y0 + 13)
.attr("dy", ".75em")
.text(xlabel2);
el.append("text").attr("class", "y label")
.attr("text-anchor", "end")
.attr("x", -100)
.attr("y", x0)
.attr("dy", "-.75em")
.attr("transform", "rotate(-90)")
.text(ylabel);
// And labels.
el.append("text").attr("text-anchor", "middle")
.attr("x", 230)
.attr("y", 205)
.text(anna2015);
el.append("text").attr("text-anchor", "middle")
.attr("x", 600)
.attr("y", 170)
.text(anna2016);
el.append("text").attr("text-anchor", "middle")
.attr("x", 230)
.attr("y", 80)
.text(judy2015);
el.append("text").attr("text-anchor", "middle")
.attr("x", 600)
.attr("y", 70)
.text(judy2016);
// And names.
el.append("text").attr("text-anchor", "right")
.attr("x", 635)
.attr("y", 140)
.attr("fill", "red")
.text(annaname);
el.append("text").attr("text-anchor", "right")
.attr("x", 635)
.attr("y", 40)
.attr("fill", "blue")
.text(judyname);
// And a title.
el.append("text").attr("class", "title")
.attr("text-anchor", "middle")
.attr("x", width/2)
.attr("y", -10)
.text(title);
return xkcd;
};
// Adding plot elements.
xkcd.plot = function (data, opts) {
var x = function (d) { return d.x; },
y = function (d) { return d.y; },
cx = function (d) { return xscale(x(d)); },
cy = function (d) { return yscale(y(d)); },
xl = d3.extent(data, x),
yl = d3.extent(data, y);
// Rescale the axes.
xlim = xlim || xl;
xlim[0] = Math.min(xlim[0], xl[0]);
xlim[1] = Math.max(xlim[1], xl[1]);
ylim = ylim || yl;
ylim[0] = Math.min(ylim[0], yl[0]);
ylim[1] = Math.max(ylim[1], yl[1]);
// Add the plotting function.
elements.push({
data: data,
func: lineplot,
x: cx,
y: cy,
opts: opts
});
return xkcd;
};
// Plot styles.
function lineplot(data, x, y, opts) {
var line = d3.svg.line().x(x).y(y).interpolate(xinterp),
bgline = d3.svg.line().x(x).y(y),
strokeWidth = _get(opts, "stroke-width", 3),
color = _get(opts, "stroke", "steelblue");
el.append("svg:path").attr("d", bgline(data))
.style("stroke", "white")
.style("stroke-width", 2 * strokeWidth + "px")
.style("fill", "none")
.attr("class", "bgline");
el.append("svg:path").attr("d", line(data))
.style("stroke", color)
.style("stroke-width", strokeWidth + "px")
.style("fill", "none");
};
// XKCD-style line interpolation. Roughly based on:
// jakevdp.github.com/blog/2012/10/07/xkcd-style-plots-in-matplotlib
function xinterp (points) {
// Scale the data.
var f = [xscale(xlim[1]) - xscale(xlim[0]),
yscale(ylim[1]) - yscale(ylim[0])],
z = [xscale(xlim[0]),
yscale(ylim[0])],
scaled = points.map(function (p) {
return [(p[0] - z[0]) / f[0], (p[1] - z[1]) / f[1]];
});
// Compute the distance along the path using a map-reduce.
var dists = scaled.map(function (d, i) {
if (i == 0) return 0.0;
var dx = d[0] - scaled[i - 1][0],
dy = d[1] - scaled[i - 1][1];
return Math.sqrt(dx * dx + dy * dy);
}),
dist = dists.reduce(function (curr, d) { return d + curr; }, 0.0);
// Choose the number of interpolation points based on this distance.
var N = Math.round(200 * dist);
// Re-sample the line.
var resampled = [];
dists.map(function (d, i) {
if (i == 0) return;
var n = Math.max(3, Math.round(d / dist * N)),
spline = d3.interpolate(scaled[i - 1][1], scaled[i][1]),
delta = (scaled[i][0] - scaled[i - 1][0]) / (n - 1);
for (var j = 0, x = scaled[i - 1][0]; j < n; ++j, x += delta)
resampled.push([x, spline(j / (n - 1))]);
});
// Compute the gradients.
var gradients = resampled.map(function (a, i, d) {
if (i == 0) return [d[1][0] - d[0][0], d[1][1] - d[0][1]];
if (i == resampled.length - 1)
return [d[i][0] - d[i - 1][0], d[i][1] - d[i - 1][1]];
return [0.5 * (d[i + 1][0] - d[i - 1][0]),
0.5 * (d[i + 1][1] - d[i - 1][1])];
});
// Normalize the gradient vectors to be unit vectors.
gradients = gradients.map(function (d) {
var len = Math.sqrt(d[0] * d[0] + d[1] * d[1]);
return [d[0] / len, d[1] / len];
});
// Generate some perturbations.
var perturbations = smooth(resampled.map(d3.random.normal()), 3);
// Add in the perturbations and re-scale the re-sampled curve.
var result = resampled.map(function (d, i) {
var p = perturbations[i],
g = gradients[i];
return [(d[0] + magnitude * g[1] * p) * f[0] + z[0],
(d[1] - magnitude * g[0] * p) * f[1] + z[1]];
});
return result.join("L");
}
// Smooth some data with a given window size.
function smooth(d, w) {
var result = [];
for (var i = 0, l = d.length; i < l; ++i) {
var mn = Math.max(0, i - 5 * w),
mx = Math.min(d.length - 1, i + 5 * w),
s = 0.0;
result[i] = 0.0;
for (var j = mn; j < mx; ++j) {
var wd = Math.exp(-0.5 * (i - j) * (i - j) / w / w);
result[i] += wd * d[j];
s += wd;
}
result[i] /= s;
}
return result;
}
// Get a value from an object or return a default if that doesn't work.
function _get(d, k, def) {
if (typeof d === "undefined") return def;
if (typeof d[k] === "undefined") return def;
return d[k];
}
return xkcd;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment