Created
August 28, 2015 19:24
-
-
Save nicoguaro/207b9853a777f61d447c to your computer and use it in GitHub Desktop.
Vertical barchart using D3 and reading data from a tab separated fiel.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
name | value | |
---|---|---|
Locke | 4 | |
Reyes | 8 | |
Ford | 12 | |
Jarrah | 16 | |
Shephard | 23 | |
Kwon | 42 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- | |
Available at: | |
http://bl.ocks.org/mbostock/7452541 | |
--> | |
<!DOCTYPE html> | |
<meta charset="utf-8"> | |
<style> | |
.chart rect { | |
fill: steelblue; | |
} | |
.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; | |
var y = d3.scale.linear() | |
.range([height, 0]); | |
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.value; })]); | |
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") | |
.attr("y", function(d) { return y(d.value); }) | |
.attr("height", function(d) { return height - y(d.value); }) | |
.attr("width", barWidth - 1); | |
bar.append("text") | |
.attr("x", barWidth / 2) | |
.attr("y", function(d) { return y(d.value) + 3; }) | |
.attr("dy", ".75em") | |
.text(function(d) { return d.value; }); | |
}); | |
function type(d) { | |
d.value = +d.value; // coerce to number | |
return d; | |
} | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment