Skip to content

Instantly share code, notes, and snippets.

@chilijung
Created April 18, 2014 04:27
Show Gist options
  • Save chilijung/11024799 to your computer and use it in GitHub Desktop.
Save chilijung/11024799 to your computer and use it in GitHub Desktop.
Bar chart in svg
name weight
Mary 60
Chi 70
Chen 45
Jack 65
Weber 66
Kevin 80
<html>
<head>
<style>
.chart rect {
fill: steelblue;
}
.chart text {
fill: white;
font: 10px sans-serif;
text-anchor: end;
}
</style>
</head>
<body>
<svg class="chart">
</svg>
<script src="//cdnjs.cloudflare.com/ajax/libs/d3/3.4.5/d3.js"></script>
<script>
var width = 420;
var barHeight = 20;
d3.csv('./data.csv', type, function(data) {
// scale
var x = d3.scale.linear()
.domain([0, d3.max(data, function(d) {return d.weight;})])
.range([0, width]);
var chart = d3.select('.chart')
.attr('width', width)
.attr('height', barHeight * data.length);
var bar = chart.selectAll('g')
.data(data)
.enter()
.append('g')
.attr('transform', function(d, i) {return "translate(0, " + i * barHeight + ")"});
bar.append('rect')
.attr('width', function(d) {return x(d.weight)})
.attr('height', barHeight -1);
bar.append('text')
.attr('x', function(d) {return x(d.weight) -3 })
.attr('y', barHeight / 2)
.attr('dy', '.35em')
.text(function(d) {return d.name})
})
function type(d) {
d.weight = +d.weight; // coerce to number
return d;
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment