This reproduces mbostock’s vertical bar chart example with the full source.
I ran into a bunch of problems trying to follow the tutorial, so it’s instructive to put the entire source here—with my own cosmetic tweaks.
This reproduces mbostock’s vertical bar chart example with the full source.
I ran into a bunch of problems trying to follow the tutorial, so it’s instructive to put the entire source here—with my own cosmetic tweaks.
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="utf-8"> | |
<script src="http://d3js.org/d3.v3.min.js"></script> | |
<style type="text/css"> | |
line, rect { | |
shape-rendering: crispEdges; | |
} | |
.chart rect { | |
fill: steelblue; | |
stroke: #FFF; | |
} | |
text { | |
fill: #FFF; | |
font: 10px sans-serif; | |
} | |
.rule, .rule text { | |
fill: #000; | |
} | |
.divider { | |
stroke: #CCC; | |
} | |
.origin { | |
stroke: #000; | |
} | |
</style> | |
</head> | |
<body> | |
<script type="text/javascript"> | |
var data = [4, 8, 15, 16, 23, 42]; | |
var barHeight = 20; | |
var padding = 20; | |
var w = 420; | |
var h = barHeight * data.length; | |
var x = d3.scale.linear() | |
.domain([0, d3.max(data)]) // input range | |
.range([0, w]); // width | |
var y = d3.scale.ordinal() | |
.domain(data) | |
.rangeBands([0, h]); | |
var chart = d3.select("body") | |
.append("svg") | |
.attr({ | |
"class": "chart", | |
"width": w + padding, | |
"height": h + padding | |
}) | |
.append("g") | |
.attr("transform", "translate(10,15)"); | |
chart.selectAll("line") | |
// Place this before the rect to avoid overlap | |
.data(x.ticks(10)) | |
.enter() | |
.append("line") | |
.attr("class", "divider") | |
.attr("x1", x) | |
.attr("x2", x) | |
.attr("y1", 0) | |
.attr("y2", h); | |
chart.selectAll("rect") | |
.data(data) | |
.enter() | |
.append("rect") | |
.attr({ | |
"y": y, | |
"width": x, | |
"height": y.rangeBand() | |
}); | |
chart.selectAll("text") | |
.data(data) | |
.enter() | |
.append("text") | |
.attr({ | |
"x": x, | |
"y": function(d) { | |
return y(d) + y.rangeBand() / 2; }, | |
"dx": -3, // padding-right | |
"dy": ".35em", // vertical-align: middle | |
"text-anchor": "end" // text-align: right | |
}) | |
.text(String); | |
chart.selectAll(".rule") | |
.data(x.ticks(10)) | |
.enter() | |
.append("text") | |
.attr({ | |
"class": "rule", | |
"x": x, | |
"y": 0, | |
"dy": -3, | |
"text-anchor": "middle" | |
}) | |
.text(String); | |
chart.append("line") | |
.attr({ | |
"class": "origin", | |
"y1": 0, | |
"y2": h | |
}); | |
</script> | |
</body> | |
</html> |