D3 Histogram of letters
by Dan Shahin
HTML
<script src="http://d3js.org/d3.v3.min.js"></script>
<body>
<label for="input">type anything in the box</label><br/>
<textarea name="input" id="input" cols="30" rows="10">
When in the Course of human events, it becomes necessary for one people to dissolve the political bands which have connected them with another, and to assume among the powers of the earth, the separate and equal station to which the Laws of Nature and of Nature's God entitle them, a decent respect to the opinions of mankind requires that they should declare the causes which impel them to the separation.
</textarea>
<button id="sort" >Sort</button>
</body>
CSS
#input{
width:100%;
}
rect {
-moz-transition: all 0.3s;
-webkit-transition: all 0.3s;
-o-transition: all 0.3s;
transition: all 0.3s;
}
rect:hover{
fill: Tomato;
}
JavaScript
$('#input').keyup(function(){
var txt = $('#input').val().toUpperCase(),
chars = txt.split(""),
len = chars.length,
histo = {};
for(var i=0;i<len;i++){
var char = chars[i];
//keys.push(char);
if(char.match(/\w/)){
if (histo[char]){
histo[char]++;
}else{
histo[char] = 1;
}
}
}
console.log(keys);
$('svg').remove();
console.log(histo);
var w = 600;
var h = 250;
var dataset = [];
var keys = [];
for(var p in histo){
keys.push(p);
}
keys = keys.sort();
var keyLength = keys.length;
for(var i=0; i< keyLength; i++){
var key = keys[i];
dataset.push({key: key, value: histo[key]});
}
var xScale = d3.scale.ordinal()
.domain(d3.range(dataset.length))
.rangeRoundBands([0, w], 0.05);
var yScale = d3.scale.linear()
.domain([0, d3.max(dataset, function(d) {return d.value;})])
.range([0, h]);
var key = function(d) {
return d.key;
};
//Create SVG element
var svg = d3.select("body")
.append("svg")
.attr("width", w)
.attr("height", h);
//Create bars
svg.selectAll("rect")
.data(dataset, key)
.enter()
.append("rect")
.attr("x", function(d, i) {
return xScale(i);
})
.attr("y", function(d) {
return h - yScale(d.value);
})
.attr("width", xScale.rangeBand())
.attr("height", function(d) {
return yScale(d.value);
})
.attr("fill", function(d) {
//return "rgb(0, 0, " + (d.value * 10) + ")";
return "rgb(150, " + (d.value * 10) + ",200)";
});
//Create labels
svg.selectAll("text")
.data(dataset, key)
.enter()
.append("text")
.text(function(d) {
return...