Skip to content

Instantly share code, notes, and snippets.

@vitorbal
Created February 7, 2013 09:46
Show Gist options
  • Save vitorbal/4729900 to your computer and use it in GitHub Desktop.
Save vitorbal/4729900 to your computer and use it in GitHub Desktop.
rank bar chart
{"description":"rank bar chart","endpoint":"","display":"svg","public":true,"require":[],"fileconfigs":{"inlet.js":{"default":true,"vim":false,"emacs":false,"fontSize":12},"config.json":{"default":true,"vim":false,"emacs":false,"fontSize":12},"_.md":{"default":true,"vim":false,"emacs":false,"fontSize":12}},"play":false,"loop":false,"restart":false,"autoinit":true,"pause":true,"loop_type":"period","bv":false,"nclones":15,"clone_opacity":0.4,"duration":3000,"ease":"linear","dt":0.01}
var data = [{ 'name': 'London', 'total': 14058, 'percentage': 17 },
{ 'name': 'Munich', 'total': 9927, 'percentage': 8 },
{ 'name': 'Paris', 'total': 7920, 'percentage': 6 },
{ 'name': 'New York', 'total': 3615, 'percentage': 5 },
{ 'name': 'Singapore', 'total': 1707, 'percentage': 4 },
{ 'name': 'Istanbul', 'total': 1305, 'percentage': 3 },
{ 'name': 'Madrid', 'total': 402, 'percentage': 1 }];
var maxWidth = 350;
var maxHeight = 220;
var svg = d3.select('svg').append('g');
var formatPercent = d3.format('.%');
var xscale = d3.scale.linear()
.domain([0, d3.max(data, function(d) { return d.total; })])
.range([0, maxWidth]);
var yscale = d3.scale.ordinal()
.domain(data.map(function(d) { return d.name; }))
.rangeRoundBands([0, maxHeight], .2);
var rect = svg.selectAll('rect').data(data);
rect.enter()
.append('rect')
.style({
fill: 'steelblue',
'font-size': '14px',
'font-famly': 'Helvetica Neue'
})
.attr({
x: 120,
width: 0,
y: function(d, i) { return 44 + yscale(d.name); },
height: yscale.rangeBand(),
});
rect.transition()
.duration(800)
.attr({ width: function(d) { return xscale(d.total); } });
svg.selectAll('text.label')
.data(data)
.enter()
.append('text')
.attr('class', 'label')
.style('text-anchor', 'end')
.text(function(d) { return d.name; })
.attr({
x: 110,
y: function(d, i) { return 63 + yscale(d.name); }
});
var percentage = svg.selectAll('text.percentage').data(data);
percentage.enter()
.append('text')
.attr('class', percentage)
.text(function(d) { return d.percentage + '%'; })
.attr({
x: 128,
y: function(d, i) { return 63 + yscale(d.name); }
})
percentage.transition()
.duration(800)
.attr({ x: function(d) { return 128 + xscale(d.total); } });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment