|
<!DOCTYPE html> |
|
<meta charset="utf-8"> |
|
<style> |
|
|
|
text { |
|
font: bold 48px monospace; |
|
} |
|
|
|
.enter { |
|
fill: green; |
|
} |
|
|
|
.update { |
|
fill: #333; |
|
} |
|
|
|
.exit { |
|
fill: brown; |
|
} |
|
|
|
</style> |
|
<body> |
|
<script src="http://d3js.org/d3.v2.min.js?2.10.1"></script> |
|
<script> |
|
|
|
var width = 960, |
|
height = 500, |
|
names, |
|
i=0; |
|
|
|
var svg = d3.select("body").append("svg") |
|
.attr("width", width) |
|
.attr("height", height) |
|
.append("g") |
|
.attr("transform", "translate(32," + (height / 2) + ")"); |
|
|
|
d3.csv("prez.csv", |
|
function(data, error) { |
|
callbackError = error; |
|
callbackData = data; |
|
doStuff(data); |
|
}); |
|
|
|
var letterSeperation = 35; |
|
var transitionTime = 750; |
|
var timeBetweenNames = 1500; |
|
|
|
function doStuff(data) { |
|
names = data; |
|
|
|
function update(data) { |
|
// data becomes an array of letters/spaces |
|
data = data.Prez.split(""); |
|
|
|
// this should go in a function |
|
var tempData = []; |
|
var letterCount = {}; |
|
data.forEach(function(letter) { |
|
var count = letterCount[letter]; |
|
if (count === undefined) { |
|
count = 0; |
|
} |
|
tempData.push({letter: letter, incidence: count}); |
|
letterCount[letter] = count + 1; |
|
}); |
|
data = tempData; |
|
//console.log(JSON.stringify(data, null, 2)); |
|
|
|
// DATA JOIN |
|
// Join new data with old elements, if any. |
|
var text = svg.selectAll("text") |
|
.data(data, function(d) { return d.letter + d.incidence; }); |
|
|
|
// UPDATE |
|
// Update old elements as needed. |
|
text.attr("class", "update") |
|
.attr("y", 0) // fixes any incomplete transitions hopefully |
|
.transition() |
|
.duration(transitionTime) |
|
.attr("x", function(d, i) { return i * letterSeperation; }); |
|
|
|
// ENTER |
|
// Create new elements as needed. |
|
text.enter().append("text") |
|
.attr("class", "enter") |
|
.attr("dy", ".35em") |
|
.attr("y", -60) |
|
.attr("x", function(d, i) { return i * letterSeperation; }) |
|
.style("fill-opacity", 0) |
|
.text(function(d) { return d.letter; }) |
|
.transition() |
|
.duration(transitionTime) |
|
.attr("y", 0) |
|
.style("fill-opacity", 1); |
|
|
|
// EXIT |
|
// Remove old elements as needed. |
|
text.exit() |
|
.attr("class", "exit") |
|
.transition() |
|
.duration(transitionTime) |
|
.attr("y", 60) |
|
.style("fill-opacity", 0) |
|
.remove(); |
|
} |
|
|
|
// The initial display. |
|
update(names[randomIndex(names.length)]); |
|
|
|
// Grab a random sample of letters from the alphabet, in alphabetical order. |
|
setInterval(function() { |
|
//update(shuffle(alphabet) |
|
// .slice(0, Math.floor(Math.random() * 26)) |
|
// .sort()); |
|
update(names[randomIndex(names.length)]); |
|
}, timeBetweenNames); |
|
|
|
|
|
function randomIndex(array) { |
|
return Math.floor(Math.random()*names.length); |
|
} |
|
} |
|
|
|
</script> |