Created
July 31, 2013 05:12
-
-
Save yxkelan/6119466 to your computer and use it in GitHub Desktop.
#D3 Bar chart, from 'Interactive data visualization for web'
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var dataset = [5, 10, 13, 19, 21, 25, 22, 18, 15, 14, 11, 12, 20, 18, 17, 16, 18, 23, 25]; | |
var w = 600, h = 250; | |
var xScale = d3.scale.ordinal().domain(d3.range(dataset.length)) | |
.rangeRoundBands([0, w], 0.05); | |
var yScale = d3.scale.linear().domain([0, d3.max(dataset)]) | |
.range([0, h]); | |
// Create SVG element | |
var svg = d3.select('body').append('svg') | |
.attr('width',w).attr('height',h); | |
// Create bars | |
svg.selectAll('rect').data(dataset).enter().append('rect') | |
.attr('x', function(d,i){ return xScale(i); }) | |
.attr('width', xScale.rangeBand()) | |
.attr('y', function(d){return h-yScale(d);}) | |
.attr('height', function(d){ return yScale(d);}) | |
.style('fill', function(d){ return "rgb(0,0,"+(d*10)+")"; }); | |
//Create labels | |
svg.selectAll('text').data(dataset).enter().append('text') | |
.text(function(d){ return d;}) | |
.attr('text-anchor', 'middle') | |
.attr('x', function(d, i){ return xScale(i)+xScale.rangeBand()/2;}) | |
.attr('y', function(d){ return h-yScale(d)+14;}) | |
.attr('font-family', 'sans-serif') | |
.attr('font-size','11px') | |
.style('fill','white'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment