Skip to content

Instantly share code, notes, and snippets.

@willscripted
Created November 27, 2012 15:44
Show Gist options
  • Save willscripted/4154931 to your computer and use it in GitHub Desktop.
Save willscripted/4154931 to your computer and use it in GitHub Desktop.
Horizontal Graph

Following the D3.js bar chart example, throwing in error bars and a transition just for kicks.

<!DOCTYPE html>
<meta charset="utf-8">
<style>
.chart {
font: 10px sans-serif;
}
.chart rect {
fill: steelblue;
stroke: white;
}
.chart line {
stroke: black;
}
.chart .rule {
fill: #ccc;
}
.chart .label {
fill: white;
}
</style>
<body>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
var data = [4, 8, 15, 16, 23, 42];
var error = 4;
var x = d3.scale.linear()
.domain([0, d3.max(data) + error])
.range([0, 420]);
var y = d3.scale.ordinal()
.domain(data)
.rangeBands([0, 120]);
// SVG
var chart = d3.select("body").append("svg")
.attr("class", "chart")
.attr("width", 440)
.attr("height", 140)
.append("g")
.attr("transform", "translate(10,15)");
// Ticks
chart.selectAll("line.tick") // Lines
.data(x.ticks(10))
.enter().append("line")
.attr("class", "tick")
.attr("x1", x)
.attr("x2", x)
.attr("y1", 0)
.attr("y2", 120)
.style("stroke", "#ccc");
chart.selectAll(".rule") // Line text
.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") // Baseline
.attr("y1", 0)
.attr("y2", 120)
.style("stroke", "#000");
// Bars
chart.selectAll("rect") // Values
.data(data)
.enter().append("rect")
.attr("y", y)
.attr("height", y.rangeBand())
.transition()
.duration(1000)
.attr("width", x);
chart.selectAll("polyline.error") // Error bars
.data(data)
.enter().append("polyline")
.attr("class", "error")
.style("stroke", "#CCC")
.attr("points", function(d){
var x1 = x(d - error)
, x2 = x(d + error)
, ym = y(d) + y.rangeBand() / 2
, yt = ym + y.rangeBand() * 1/3
, yb = ym - y.rangeBand() * 1/3
return "" + x1 + "," + yt + " "
+ x1 + "," + yb + " "
+ x1 + "," + ym + " "
+ x2 + "," + ym + " "
+ x2 + "," + yt + " "
+ x2 + "," + yb + " "
+ x2 + "," + ym + " "
+ x1 + "," + ym + " ";
})
chart.selectAll(".label") // Value Labels
.data(data)
.enter().append("text")
.attr("class", "label")
.attr("x", x)
.attr("y", function(d) {return y(d) + y.rangeBand() / 2; })
.attr("dx", -3)
.attr("dy", ".35em")
.attr("text-anchor", "end")
.text(String);
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment