Skip to content

Instantly share code, notes, and snippets.

@ndarville ndarville/
Last active Dec 17, 2015

What would you like to do?
mbostock’s vertical bar chart example

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">
<meta charset="utf-8">
<script src=""></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;
<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()
.rangeBands([0, h]);
var chart ="body")
"class": "chart",
"width": w + padding,
"height": h + padding
.attr("transform", "translate(10,15)");
// Place this before the rect to avoid overlap
.attr("class", "divider")
.attr("x1", x)
.attr("x2", x)
.attr("y1", 0)
.attr("y2", h);
"y": y,
"width": x,
"height": y.rangeBand()
"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
"class": "rule",
"x": x,
"y": 0,
"dy": -3,
"text-anchor": "middle"
"class": "origin",
"y1": 0,
"y2": h
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.