Skip to content

Instantly share code, notes, and snippets.

@mbostock
Last active December 13, 2021 00:58
Show Gist options
  • Save mbostock/3310560 to your computer and use it in GitHub Desktop.
Save mbostock/3310560 to your computer and use it in GitHub Desktop.
Letter Frequency
license: gpl-3.0

D3 2.10 adds support for optional outer padding with d3.scale.ordinal. This parameter allows you to control the outer padding (before the first bar and after the last bar) separately from the inner padding between bars. In this case, the inner padding is 10% and the outer padding is 20%.

var x = d3.scale.ordinal()
    .rangeRoundBands([0, width], 0.1, 0.2);

See also this updated version with an axis title.

<!DOCTYPE html>
<meta charset="utf-8">
<style>
body {
font: 10px sans-serif;
}
.axis path,
.axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
.bar {
fill: steelblue;
}
.x.axis path {
display: none;
}
</style>
<body>
<script src="//d3js.org/d3.v3.min.js"></script>
<script>
var margin = {top: 20, right: 30, bottom: 30, left: 40},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var x = d3.scale.ordinal()
.rangeRoundBands([0, width], 0.1, 0.2);
var y = d3.scale.linear()
.range([height, 0]);
var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
d3.tsv("letter-frequency.tsv", type, function(error, letters) {
x.domain(letters.map(function(d) { return d.letter; }));
y.domain([0, d3.max(letters, function(d) { return d.frequency; })]);
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(d3.svg.axis().scale(x).orient("bottom"));
svg.append("g")
.attr("class", "y axis")
.call(d3.svg.axis().scale(y).orient("left"));
svg.selectAll(".bar")
.data(letters)
.enter().append("rect")
.attr("class", "bar")
.attr("x", function(d) { return x(d.letter); })
.attr("width", x.rangeBand())
.attr("y", function(d) { return y(d.frequency); })
.attr("height", function(d) { return height - y(d.frequency); });
});
function type(d) {
d.frequency = +d.frequency;
return d;
}
</script>
letter frequency
A .08167
B .01492
C .02780
D .04253
E .12702
F .02288
G .02022
H .06094
I .06973
J .00153
K .00747
L .04025
M .02517
N .06749
O .07507
P .01929
Q .00098
R .05987
S .06333
T .09056
U .02758
V .01037
W .02465
X .00150
Y .01971
Z .00074
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment