Skip to content

Instantly share code, notes, and snippets.

@auremoser
Last active November 23, 2016 15:01
Show Gist options
  • Save auremoser/4cdb347270cdd527fe76bdf8ceea1405 to your computer and use it in GitHub Desktop.
Save auremoser/4cdb347270cdd527fe76bdf8ceea1405 to your computer and use it in GitHub Desktop.
D3 Bar Vis 2
letter frequency
A .08167
B .01492
C .02782
D .04253
E .12702
F .02288
G .02015
H .06094
I .06966
J .00153
K .00772
L .04025
M .02406
N .06749
O .07507
P .01929
Q .00095
R .05987
S .06327
T .09056
U .02758
V .00978
W .02360
X .00150
Y .01974
Z .00074
<!DOCTYPE html>
<meta charset="utf-8">
<style>
.chart rect {
fill: #dc0045;
}
.chart text {
fill: white;
font: 10px sans-serif;
text-anchor: middle;
}
</style>
<svg class="chart"></svg>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
var width = 960,
height = 500;
//Helper Functions
var y = d3.scale.linear()
.range([height, 0]);//svg 0 is on top the screen
//Viz
var chart = d3.select(".chart")
.attr("width", width)
.attr("height", height);
d3.tsv("data.tsv", type, function(error, data) {
y.domain([0, d3.max(data, function(d) { return d.frequency; })]);//array of objects
var barWidth = width / data.length;
var bar = chart.selectAll("g")//group
.data(data)
.enter().append("g")
.attr("transform", function(d, i) { return "translate(" + i * barWidth + ",0)"; });//svg property
//https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/transform
bar.append("rect")
.attr("y", function(d) { return y(d.frequency); })
.attr("height", function(d) { return height - y(d.frequency); })
.attr("width", barWidth - 1);
bar.append("text")
.attr("x", barWidth / 2)
.attr("y", function(d) { return y(d.frequency) + 3; })//so it is on top
.attr("dy", ".75em")//TODO .em
.text(function(d) { return d.frequency; });
});
function type(d) {
d.frequency = +d.frequency;// coerce to number
return d;
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment