Skip to content

Instantly share code, notes, and snippets.

@EmbraceLife
Last active August 1, 2016 03:23
Show Gist options
  • Save EmbraceLife/ea98cae3b044803598b3b54fbb969abc to your computer and use it in GitHub Desktop.
Save EmbraceLife/ea98cae3b044803598b3b54fbb969abc to your computer and use it in GitHub Desktop.
2. vertical barChart
license: gpl-3.0

Key

  1. padding is done by barWidth - 1
name value
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: orange;
}
.chart text {
fill: steelblue;
font: 10px sans-serif;
text-anchor: middle;
}
</style>
<svg class="chart"></svg>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>
var width = 960,
height = 500;
var chart = d3.select(".chart")
.attr("width", width)
.attr("height", height);
var yScale = d3.scaleLinear()
// set px-range: from bottom to top => [height, 0]
.range([height, 0]);
function type(d) {
// coerce into numeric values from string
// round decimal using Math.round*100/100
d.value = Math.round(+d.value*100)/100;
return d;
}
d3.tsv("data.tsv", type, function(error, data) {
yScale.domain([0, d3.max(data, function(d) { return d.value; })]);
// set barWidth using SVG's width / data.length
var barWidth = width / data.length;
var bar = chart.selectAll("g")
.data(data)
.enter()
.append("g")
.attr("transform", function(d, i) { return "translate(" + i * barWidth + ",0)"; });
bar.append("rect")
// rect's y coord default is 0 inherited from g
// set each rect's topLeft corner's "y" coord
.attr("y", function(d) { return yScale(d.value); })
// set each rect's height using canvas height and y coord
.attr("height", function(d) { return height - yScale(d.value); })
.attr("width", barWidth - 1);
// step 7
bar.append("text")
// set each text's x coord
.attr("x", barWidth / 2)
// set each text's y coord
.attr("y", function(d) { return yScale(d.value) + 3; })
.attr("dy", ".75em")
.text(function(d) { return d.value; });
// attr text-anchor is set to middle
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment