D3
by beau
HTML
<script src="http://underscorejs.org/underscore-min.js"></script>
<script src="http://d3js.org/d3.v2.min.js"></script>
<div class="chart"></div>
CSS
.chart {
font: 10px sans-serif;
}
JavaScript
// feel free to edit the data. the graph will scale
var data = [30, 72, 11, 100, 52, 99, 12, 30];
// or sort the data
// data = _(data).sortBy(_.identity);
////////////////////////////////////////////////////
// Create the SVG with some inner padding
var chart = d3.select(".chart")
.append("svg:svg")
.attr("width", 560)
.attr("height", 360)
.append("g")
.attr("transform", "translate(30,30)");
// Create the x and y scales
var x = d3.scale.linear()
.domain([0, d3.max(data)])
.range([0, 500]);
var y = d3.scale.ordinal()
.domain(data)
.rangeBands([0, 120]);
// draw the vertical tick marks
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");
// tick marks come first in the code, so they appear
// *under* the bars
// add text above each tick mark
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);
// draw the rectangles
chart.selectAll('rect').data(data)
.enter().append('rect')
.style("stroke", "black")
.style("fill", "lightblue")
.attr("y", y)
.attr("height", y.rangeBand())
.attr("width", x)
.on("mouseover", function(){
d3.select(this).style("fill", "steelblue");
})
.on("mouseout", function(){
d3.select(this).style("fill", "lightblue");
});
// add text to the end of each bar
chart.selectAll(".info").data(data)
.enter().append("text")
.attr("class", "info")
.attr("x", x)
.attr("y", function(d) { return y(d) + y.rangeBand() / 2; })
.attr("dx", -3) // padding-right
.attr("dy", ".35em") // vertical-align: middle
...