Created
May 6, 2012 14:23
-
-
Save hdemers/2622510 to your computer and use it in GitHub Desktop.
D3.js bar chart tutorial, part 1
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
<!doctype html> | |
<html> | |
<head> | |
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> | |
<title>D3.js sandbox</title> | |
<script src="http://d3js.org/d3.v2.js"></script> | |
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> | |
<script src="http://documentcloud.github.com/underscore/underscore-min.js"></script> | |
<style type="text/css"> | |
.chart rect { | |
stroke: white; | |
fill: steelblue; | |
} | |
.chart text { | |
fill: white; | |
font-size: 11pt; | |
} | |
.chart text.rule { | |
fill: gray; | |
} | |
</style> | |
</head> | |
<body id="body"> | |
<p> | |
Example from the tutorial | |
<a href="http://mbostock.github.com/d3/tutorial/bar-1.html"> | |
A Bar Chart, Part 1. | |
</a> | |
</p> | |
<svg></svg> | |
<script type="text/javascript"> | |
var data = [4, 8, 15, 16, 23, 42], | |
chart = d3.select("svg") | |
.attr("class", "chart") | |
.attr("width", 440) | |
.attr("height", 25 * data.length) | |
.append("g").attr("transform", "translate(10, 15)"), | |
x = d3.scale.linear() | |
.domain([0, d3.max(data)]) | |
.range([0, 420]), | |
y = d3.scale.ordinal() | |
.domain(data) | |
.rangeBands([0, 120]); | |
chart.selectAll("line") | |
.data(x.ticks(10)) | |
.enter().append("line") | |
.attr("x1", x) | |
.attr("x2", x) | |
.attr("y1", 0) | |
.attr("y2", 120) | |
.style("stroke", "#ccc"); | |
chart.selectAll("rect") | |
.data(data) | |
.enter().append("rect") | |
.attr("y", y) | |
.attr("width", x) | |
.attr("height", 20); | |
chart.selectAll("text") | |
.data(data) | |
.enter().append("text") | |
.attr("x", x) | |
.attr("y", function(d) { return y(d) + y.rangeBand() / 2; }) | |
.attr("dx", -3) // padding-right | |
.attr("dy", ".35em") // vertical-align: middle | |
.attr("text-anchor", "end") // text-align: right | |
.text(String); | |
chart.selectAll(".rule") | |
.data(x.ticks(10)) | |
.enter().append("text") | |
.attr("class", "rule") | |
.attr("x", x) | |
.attr("y", 0) | |
.attr("dy", -3) | |
.attr("text-anchor", "middle") | |
.text(String); | |
chart.append("line") | |
.attr("y1", 0) | |
.attr("y2", 120) | |
.style("stroke", "#000"); | |
</script> | |
</body> | |
</html> | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment